Why does getElementById is not working for me? In Java

Viewed 417

I am trying to get an element by id in Java with Document object (org.w3c.dom.Document), but when I use the function getElementById(elementId) is returning a null. The Document Object is creating Ok, because I use getElementByTags and works fine.

My code in Java:

DocumentBuilder dbRespuesta0 = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document docRespuesta0 = dbRespuesta0.parse(new InputSource(new StringReader(context.getProperty("XML").toString())));
Element e = (Element) docRespuesta0.getElementById("ID_X");

The structure of my XML

<RESULT>
    <TAG1 ID="A">
        
    </TAG1>
    <TAG1 ID="B">
       
    </TAG1>
    <TAG2 DIM="30" ID="C" SIZE="2">
        
    </TAG2>
    <TAG2 DIM="300" ID="ID_X" SIZE="2">
        <TAG3 NUM="1">
            
        </TAG3>
        <TAG3 NUM="2">
           
        </TAG3>
    </TAG2>
</RESULT>

When I print the element e, I watch a null. I hope to getting in the element e, the next XML:

<TAG2 DIM="300" ID="ID_X" SIZE="2">
    <TAG3 NUM="1">

    </TAG3>
    <TAG3 NUM="2">

    </TAG3>
</TAG2>
1 Answers

You need to call setSchema(schema) to define a dom-schema that explains to the model that the attribute ID is in fact the ID of the node.

From the javadoc of org.w3c.dom.Document (https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#getElementById(java.lang.String))

Element getElementById(String elementId)

Returns the Element that has an ID attribute with the given value. If no such element exists, this returns null . If more than one element has an ID attribute with that value, what is returned is undefined. The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID.

Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.

Note the last two (highlighted) lines!

An attribute must explicitly be defined as ID, and not just be named "ID".

This question/answer gives a detailed explanation and should help you out: Java XML DOM: how are id Attributes special?

Related