0

I have the following XML loaded in an XMLElement like below:

<related_id>
  <Item>
    <classification>Component</classification>
    <id></id>
    <keyed_name>glass</keyed_name> <!-- I want to get this InnerText -->
  </Item>
</related_id>
<source_id>968C45A47942454DA9B34245A9F72A8C</source_id>
<itemtype>5E9C5A12CC58413A8670CF4003C57848</itemtype>

When I get the inner text:

string nameChildren = node.SelectSingleNode("/related_id/Item/keyed_name").InnerText;

The string is empty!

What am I doing wrong?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Daniel Camacho
  • 423
  • 5
  • 12
  • 27

2 Answers2

2

Start your XPath with a double slash, and check for default namespace (xmlns attribute) throughout the document.

The double slash means that related_id is not necessarily the top level element in the file (which it is not in your example).

If you confirm that the default namespace is defined, you will need to reflect it in your xpath like this: "//x:related_id/x:Item/x:keyed_name" and refer to this answer.

However, your XPath will still be a little suspect, because there might be more than one element with the same name at a particular level and you don't seem to handle all possible combinations safely. Double slash is somewhat dangerous in itself, unless the XML is very simple. It is usually better to start an XPath with a single slash and list all elements from the top to the bottom.

Community
  • 1
  • 1
Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75
  • Thanks!! It worked the double slash. I havent seen any tutorial which specifies. – Daniel Camacho May 09 '12 at 15:14
  • 1
    A `/` is enough to start from the root. A `//` starts from root AND accepts any nodes inbetween. If the node was not found, you would get a NullReferenceException getting it's InnerText. – Hans Kesting May 09 '12 at 15:16
1

I think you need to add namespaces, even for the default one. Try creating a XmlNamespaceManager instance and add the default namespace (e.g. "ns") to it. After that your xpath should look something like this:

/ns:related_id/ns:Item/ns:keyed_name

I think here: Using Xpath With Default Namespace in C# is the same problem you had.

Community
  • 1
  • 1
kalbsschnitzel
  • 817
  • 1
  • 8
  • 29