I want to get the 3rd node of a branching node. Example
<rows>
<row>
<cell>a</cell>
<cell>b</cell>
<cell>c</cell>
<cell>d</cell>
<cell>e</cell>
<cell>f</cell></row>
<row>
<cell>aa</cell>
<cell>bb</cell>
<cell>cc</cell>
<cell>dd</cell>
<cell>ee</cell>
<cell>ff</cell>
</row>
......
</rows>
I basically want to get item c and cc and so on out. Basically the third cell element in rows. This is what i have. However what i want are the values of the items not the xml.
var Study = XDocument.Load(XmlReader.Create(studyStream));
var rows = Study.Descendants("row");
foreach (var item in rows)
{
var cells = item.Descendants("cell");
string id = null;
foreach (var items in cells)
{
id = items.Parent.FirstNode.NextNode.NextNode.ToString();
}
Console.WriteLine(id);
}
Console.Read();
Is there a way to do this properly? Thank you for all your help.
Kevin
Well, you can do something like:
var xdoc = XDocument.Load(@"your_file.xml");
foreach (var children in xdoc.XPathSelectElements("rows/row"))
{
var thirdChild = children.Elements().Skip(2).Take(1).FirstOrDefault();
if (thirdChild != null)
Console.WriteLine(thirdChild.Value);
}
Here we first selecting /row
element and then for each such a row we selecting third child's value.
This valued collection can be also obtained without foreach
loop, only by linq query like:
var values = xdoc.XPathSelectElements("rows/row")
.Select(row => row.Elements().Skip(2).Take(1).First().Value);