GetElementById () does not find the tag?

I have a valid XML file that the following Windows.NET C # service reads. The tag in question (u1_000) is absolutely in the element:

<book id="u1_000" category="xyz"> 

Is there a reason GetElementById () cannot find the Book element with the tag? - thanks

 XmlDocument doc = new XmlDocument(); doc.Load("C:\\j.xml"); XmlElement ee = doc.GetElementById("U1_000"); <book id="U1_000" category="web"> 
+7
c # xml getelementbyid
source share
3 answers

If nothing else, maybe use xpath as a backup:

 string id = "u1_000"; string query = string.Format("//*[@id='{0}']", id); // or "//book[@id='{0}']" XmlElement el = (XmlElement)doc.SelectSingleNode(query); 
+4
source share

Check the MSDN documentation for this method . In the example below, you can see how they establish that the identifier uses DOCTYPE. This may solve the problem for you.

+3
source share

You need a DTD to set which attribute on the elements will contain a unique identifier. XML does not imply that the id attribute should be considered as a unique identifier for an element.

In general, the "unDTDed" XML getElementById is not very useful. In most cases, the structure of the XML file being processed is understood (for example, the root element is called books , which contains a series of book elements), so a typical access would look something like this: -

  XmlElement book = (XmlElement)doc.DocumentElement.SelectSingleNode("book[@ID='U1_000']"); 

If you really don't know the XML structure and / or the element tag name, then the brute force search described in Marcs answer will work.

+3
source share

All Articles