Daniel Camacho
Daniel Camacho

Reputation: 423

XML.InnerText Null

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?

Upvotes: 0

Views: 1484

Answers (2)

kalbsschnitzel
kalbsschnitzel

Reputation: 819

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.

Upvotes: 1

Jirka Hanika
Jirka Hanika

Reputation: 13529

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.

Upvotes: 2

Related Questions