Chris
Chris

Reputation: 105

GetElementById() not finding the tag?

I have a valid XML file being read by the following .NET C# windows service. The tag in question (u1_000) is absolutely in the element:

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

Is there some reason the GetElementById() does not 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"> 

Upvotes: 8

Views: 14290

Answers (3)

AnthonyWJones
AnthonyWJones

Reputation: 189467

You need a DTD to establish which attribute on elements would consitute the unique id. In XML it isn't automatically assumed that the id attribute should be treated as a unique element ID.

In general "unDTDed" XML the getElementById is not very useful. It most cases the structure of the XML file being processed is understood (for example the root element is called books that contains a series of book elements) hence 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 tag name of the element then the brute force search described in Marcs answer would work.

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1063058

If nothing else, perhaps 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);

Upvotes: 6

Scott Arrington
Scott Arrington

Reputation: 12503

Check the MSDN documentation for this method. In the sample below you can see how they establish what the ID is using the DOCTYPE. This may fix the problem for you.

Upvotes: 3

Related Questions