Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"> 
like image 359
Chris Avatar asked Jan 04 '10 23:01

Chris


People also ask

Why is document getElementById not working?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What will method getElementById () return if nothing is found?

The getElementById() method returns null if the element does not exist.

What is the getElementById () function?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Why does document getElementById show null?

When you pass in an ID which doesn't exist in the current document, getElementById returns null . Attempting to access a property of the returned value will throw the error that you're seeing. You need to debug your code to find out why the elements don't exist when you think they should.


2 Answers

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);
like image 198
Marc Gravell Avatar answered Oct 18 '22 23:10

Marc Gravell


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.

like image 35
AnthonyWJones Avatar answered Oct 18 '22 22:10

AnthonyWJones