How to grab children from xml file as a string - c#

I am looking for an occurance of a certain tag in my xml file. If i find an occurance then i want to get its immediate children tags (not their child tags)
Is this possible? If so what do i need to look in to ?
Thanks
<Footballer>
<Player>
<Number />
<Team>
<Division />
<Position />
</Team>
<Country />
<Birthdate />
</Player>
</Footballer>
if player was the input for example then the tags Number, Team, Country Birthdate would be returned

You can try to use linq to xml:
var doc = XDocument.Load(xmlFilePath);
List<string> urlList = doc.Descendants("yourparent");
.Select(x => insert value you want to select).ToList();

Related

How to get child node by number from XML file

Am trying to make sorting of data in my XML by attribute "times" and show it in TreeView
I have XML file like
<main>
<data url="http://www.r.com/" data="13.10.2013 20:16:33" times="6" />
<data url="https://www.google.com/" data="13.10.2013 20:16:14" times="5" />
<data url="http://ya.com/" data="13.10.2013 19:21:15" times="26" />
</main>
what i want is to sort all nodes by attribute "times". If i can get any of node (1, 2 or 3), that i can take attribute and compare it with first ono - so can make some sorting. but i can't get required element.
so the question - how can i get any nodes from XML file, if i know only it's serial number or how can i sort XML file by some attribute?
Found, if i have id - i can use simething like
XmlDocument myXml = new XmlDocument();
myXml.Load(myfile);
myXml.GetElementById(`here put id`).GetAttribute("required attribute")
but i havent any id.
EDIT:
<main>
<data url="http://ya.com/" data="13.10.2013 19:21:15" times="**26**" />
<data url="http://www.r.com/" data="13.10.2013 20:16:33" times="**6**" />
<data url="https://www.google.com/" data="13.10.2013 20:16:14" times="**5**" />
</main>
Am new to Linq->Xml, So I have no idea about efficiency in this but it seems to work.
XDocument xdoc = XDocument.Parse(xml);
var ordered = xdoc.Descendants("data")
.OrderByDescending(x => int.Parse(x.Attribute("times").Value))
.ToArray();
xdoc.Root.RemoveAll();
xdoc.Root.Add(ordered);
Since you want to show data in TreeView,you need to first get all the data from xml and then sort it by times
XDocument doc=XDocument.Load(url);
//extract all data from xml
var data=doc.Descendants("data")
.Select(x=>
new
{
url=x.Attribute("url").Value,
data=x.Attribute("data").Value,
times=int.Parse(x.Attribute("times").Value)
}
);
foreach(var datum in data.OrderByDescending(x=>x.times))
{
datum.url;
datum.data;
datum.times;
}

how to get the child nodes and group them from a parent node

I have a XElement object that has a structure to the one below.
How would I select all the CalcConceptId children nodes from the TestResults root node where the DataPointValue attributes are different, and store them as XElements in an array/list? I want to be able to store each child as another XElement so I can loop through them and fetch out the SeriesAsOfDate and data nodes from each one.
<TestResults RSSD="123456">
<CalcConceptId Id="110" DataPointValue="10">
<SeriesAsOfDate Value="2013-07-10T00:00:00">
<Data AsOfDate="7/10/2013" ExpectedValue="1" />
<Data AsOfDate="7/3/2013" ExpectedValue="14" />
<Data AsOfDate="6/26/2013" ExpectedValue="55" />
</SeriesAsOfDate>
</CalcConceptId>
<CalcConceptId Id="110" DataPointValue="20">
<SeriesAsOfDate Value="2013-07-10T00:00:00">
<Data AsOfDate="7/10/2013" ExpectedValue="4" />
<Data AsOfDate="7/3/2013" ExpectedValue="34" />
<Data AsOfDate="6/26/2013" ExpectedValue="1" />
</SeriesAsOfDate>
</CalcConceptId>
</TestResults>
I think you want all of the CalcConceptId nodes grouped by DataPointValue but it's a little unclear what "Where the DataPointValue is different" means.
Anyway here is what I think you want...
var calcConceptIdGroupedByDataPointValue =
doc.Descendants("CalcConceptId")
.GroupBy(calcConceptId => calcConceptId.Attribute("DataPointValue"));
I'm not 100% sure... but if I get what you're asking, are you looking for this?
//assuming the XElement is called Data:
var result =
data.Elements().GroupBy(x => int.Parse(x.Attribute("DataPointValue")))
.Select(g => g.First());

Reading XML node attribute values from nodes with the same name

My XML looks like this:
<Settings>
<Display_Settings>
<Screen>
<Name Name="Screen" />
<ScreenTag Tag="Screen Tag" />
<LocalPosition X="12" Y="81" Z="28" />
<Width Width="54" />
<Height Height="912" />
</Screen>
<Screen>
<Name Name="Screen" />
<ScreenTag Tag="Screen Tag" />
<LocalPosition X="32" Y="21" Z="28" />
<Width Width="54" />
<Height Height="912" />
</Screen>
</Display_Settings>
</Settings>
How am I able to read in the two different Local Position X attribute values from two different nodes that have the same name?
Edit
Sorry, forgot to add the code I have at the moment that reads in a singular local position attribute value from one screen node:
var xdoc = XDocument.Load("C:\\Test.xml");
var screenPosition = xdoc.Descendants("Screen").First().Element("LocalPosition");
int screenX1 = int.Parse(screenPosition1.Attribute("X").Value);
XPath would look like this:
/Settings/Display_Settings/Screen/LocalPosition/#X
You can use online tool like this: http://www.freeformatter.com/xpath-tester.html#ad-output to test your XPath's.
Also, there's a good tutorial here: http://www.w3schools.com/xpath/
As long, as question was updated, code:
var xdoc = XDocument.Load(#"C:\darbai_test\so_Test.xml");
var screenPosition = xdoc
.Descendants("Screen")
.Descendants("LocalPosition")
.Attributes("X");
foreach (var xAttribute in screenPosition)
{
Console.WriteLine(xAttribute.Value);
}
Console.ReadKey();

Reading XML Attributes into a List

I'm new to XML and am having trouble reading my XML response back from a HttpWebResponse.
Here is the response back:
<RESPONSE version="1.2">
<RESULTS>
<AN an_type="C"
an_id="783hdryfdg56a2"
an_num="1"
an_status="100" />
<RESULTS>
</RESPONSE>
I'm looking to extract out the an_id value and save it to a list. Started doing this but seems to get an for xmlnodelist as an int but it thinks nodes["an_id"] is a string
List<int> IDs = new List<int>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(returnValue);
XmlNodeList nodes = doc.SelectNodes("SEARCH_RESULTS/LOAN");
LoanIDs.Add(Convert.ToInt32(nodes["an_id"].InnerText));
Also is their a way to once the an_id's are added to a list. foreach item in the list use it as aparameter for a new xml like this:
<INPUT>
<LOGIN API_ID=""cat"" API_PASSWORD=""dog"" />
<REQUEST>
<AN an_id=""#anID"" />
<AN an_id=""#anID"" />
....foreach one in list it adds a new node with the value
</REQUEST>
</INPUT>
With xml being your string with the XML code:
var ids = XDocument.Parse(xml).
Descendants("AN").
Select(e => (string)e.Attribute("an_id")).
ToList();
However, from your sample it didn't seem that the attribute is always an integer. Are you sure about your conversion? I changed the cast of the attribute to (string) given your latest comment.
When you want to reuse the list, with current being the parent element containing the ones you want to add:
current.Add(ids.Select(i => new XElement("AN", new XAttribute("an_id", i))));

Linq - getting root descendants

The xml file is this one:
<settings y="1" x="0">
<prospect aksdj="sdf">
<image path="images/1.jpg"/>
</prospect>
<prospect aksdfasdj="safafdf">
<image path="images/2.jpg"/>
</prospect>
</settings>
I want to get both rows with the image tags.
My code is this:
XElement doc = XElement.Load(#"C:\Users\John\Desktop\File.xml");
var result = (from c in doc.Descendants("settings")
select new
{
name = c.Element("prospect").Value
}).ToList();
But, doc.Descendants("settings") is null. Why is it null?
You've loaded an element which is already the <settings> element - that element doesn't have any <settings> descendants. (Descendants isn't returning you null, by the way - it's returning you an empty sequence. There's a big difference.)
If you change it to
XDocument doc = XDocument.Load("...");
then it should be okay - or just load it as an XElement and find the <prospect> descendants, given that you've only got one <settings> element anyway...

Categories