GetElementById() not finding the tag?

Chris picture Chris · Jan 5, 2010 · Viewed 13.6k times · Source

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"> 

Answer

Marc Gravell picture Marc Gravell · Jan 5, 2010

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);