The javadoc for the Document class has the following note under getElementById.
Note: Attributes with the name “ID” or “id” are not of type ID unless so defined
So, I read an XHTML doc into the DOM (using Xerces 2.9.1).
The doc has a plain old <p id='fribble'> in it.
I call getElementById("fribble"), and it returns null.
I use XPath to get “//*[id=’fribble’]”, and all is well.
So, the question is, what causes the DocumentBuilder to actually mark ID attributes as ‘so defined?’
For the
getElementById()call to work, theDocumenthas to know the types of its nodes, and the target node must be of the XML ID type for the method to find it. It knows about the types of its elements via an associated schema. If the schema is not set, or does not declare theidattribute to be of the XML ID type,getElementById()will never find it.My guess is that your document doesn’t know the
pelement’sidattribute is of the XML ID type (is it?). You can navigate to the node in the DOM usinggetChildNodes()and other DOM-traversal functions, and try callingAttr.isId()on the id attribute to tell for sure.From the getElementById javadoc:
If you are using a
DocumentBuilderto parse your XML into a DOM, be sure to callsetSchema(schema)on the DocumentBuilderFactory before calling newDocumentBuilder(), to ensure that the builder you get from the factory is aware of element types.