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?
Start your XPath with a double slash, and check for default namespace (
xmlnsattribute) throughout the document.The double slash means that
related_idis 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.