I am using w3c DOM api in java . When I first parse my XML from an input stream and use dom.getElementById("nodeId") method , it works . But If I update my dom with some node element having ID attributes , and then tries to retrieve this node using dom.getElementById("ID"), then it doesn’t work and return null.
Any Idea ?
Thanks.
In fact the JavaDoc says something along the lines that getElementById returns the Element that has an ID attribute with the given value. An attribute with the name “ID” or “id” is not of type ID unless it is so defined.
How is an attribute defined as an ID attribute? With a DTD or schema. If you are not validating the XML, then the API is useless.
So, what to do if you want to find an element for which the attribute named “id” has a given value? Several options were offered in GetElementById Pitfalls. One of them is to use an XPath expression like this:
"//*[@id = 'myId']".Also, in the Apache XML Security project, the class
org.apache.xml.security.utils.IdResolver was specifically created to address this problem. CallingIdResolver.getElementById(doc, id)will return the element you are looking for.referhttp://www.xinotes.org/notes/note/738/
here is an example to achieve it Java: How to make getElementById() work using xml schema