0

I have to read some values from XML,below is my sample XML

<?xml version="1.0" encoding="utf-16"?>
<ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ChildNode>
    <GrandChild Name="title" Value="Mr" />
    <GrandChild Name="Name" Value="Test" />
    <GrandChild Name="Age" Value="25" />
    <GrandChild Name="Gender" Value="Male" />  
  </ChildNode>
</ParentNode>

I have to read values of Name and Age nodes, this is how I am doing

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myXMLstring);

var nodes = xmlDoc.SelectNodes("/ParentNode/ChildNode");
foreach (XmlNode childrenNode in nodes)
{
}

but this code is running for only once, I tried this inside loop,buts its not running

var gchild= childrenNode.SelectNodes("/GrandChild");
foreach (XmlNode namevalue in gchild)
{
}

How can I get the values of Name and Age node?

3
  • I don't see anything under <ChildNode>. Commented Aug 12, 2015 at 11:14
  • Modify var gchild= childrenNode.SelectNodes("/GrandChild "); to var gchild= childrenNode.SelectNodes("GrandChild "); (without leading slash) Commented Aug 12, 2015 at 11:18
  • there are <GrandChild> under <ChildNode> Commented Aug 12, 2015 at 11:19

2 Answers 2

1

Your XML contains only a single ChildNode so the XPATH expression /ParentNode/ChildNode will return only a single result. If you wanted to iterate over the grandchildren you should use /ParentNode/ChildNode/GrandChild or //GrandChild, eg:

var nodes = xmlDoc.SelectNodes("/ParentNode/ChildNode/GrandChild");

The result will be the same.

A single slash at the start of an XPath expression means that the path starts from the root, so /GrandChild returns nothing because there is no GrandChild note at the root level. A double slash // means wherever in the hierarchy, so //GrandChild will return all GrandChild nodes in the file

Sign up to request clarification or add additional context in comments.

Comments

1

SelectNodes uses XPath expressions. In XPath, if the expression stars with / it'll start selecting relative to root.

Just use a relative xpath expression. In your case:

var gchild = childrenNode.SelectNodes("./GrandChild");

Or the equivalent:

var gchild = childrenNode.SelectNodes("GrandChild");

Or, if you only aim to iterate over those GrandChild elements, there's no reason to select the ChildNode first, you could iterate directly:

var nodes = xmlDoc.SelectNodes("/ParentNode/ChildNode/GrandChild");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.