Reputation: 479
I have an XML document
<?xml version="1.0" encoding="utf-8" ?>
<data>
<string id="test-text">Some sample text from XML</string>
<string id="test-text2">Some more sample text</string>
</data>
Which I have loaded into a XmlDocument object, and I'm trying to get the text using the id. I'm probably missing something very obvious here, but this is how I'm currently trying to do it.
XmlElement elem = doc.GetElementById("test-text");
return elem.Value;
Upvotes: 0
Views: 2795
Reputation: 100545
GetElementById only work with ID attributes defined via DTD (unlikely scenario, definitely not in case of your sample):
... this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return null.
You want basic XPath with attribute check:
var d = new XmlDocument();
d.LoadXml(@"<data>
<string id='test-text'>Some sample text from XML</string>
<string id='test-text2'>Some more sample text</string>
</data>");
var elem = d.SelectSingleNode("//*[@id='test-text']");
Console.WriteLine(elem.InnerText);
Upvotes: 2
Reputation: 8551
You probably want elem.InnerText
rather than elem.Value.
From the class documentation, InnerText
Gets or sets the concatenated values of the node and all its children, while Value
is a property inherited from XmlNode
that is useful for attribute nodes, text nodes, etc. but doesn't really apply to nodes like XmlElement
. In a DOM tree built from your document, the XmlElement you're finding would contain a Text
node whose Value
is the string you're trying to retrieve.
Upvotes: 1