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">
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.
The getElementById() method returns null if the element does not exist.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With