views:

568

answers:

3

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"> 
+1  A: 

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.

Scott Anderson
+1  A: 

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);
Marc Gravell
Thanks Marc, I will go this route. Great idea. Thanks to Anthony as well.
Chris
+1  A: 

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 = (XmlLement)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.

AnthonyWJones