Java XML getElementById returning null, fix using XPath

I had almost lost my breath over this issue for an entire day and found that the solutions provided in most blogs and forums doesn't for a tight schedule.
Here, I am sharing the method that finally worked for me. I am using Netbeans with the default DOM parser(SAX Parser) provided in javax package.

The problem is that the method:

Document.getElementById(String id)

returns null unless we explicitly specify the type of an attribute as ID.
The Javadoc for this method says: "The DOM implementation must have information that says which attributes are of type ID. Attributes with the name "ID" are not of type ID unless so defined. Implementations that do not know whether attributes are of type ID or not are expected to return null."

The type of attributes can be defined in two ways, either by using a DTD or xml schema.
But, because I was really in short of time, I didn't want to go through all the complexities of implementing a DTD or XSD validation. Trust me it can really eat much time if you haven't done it before.

Writing DTD is not hard job(tutorial here), but I found that the Parser I was using(javax.xml.parsers package) doesn't implement DTD validation.

Then I found Java XPath API can be used as a quick walk through for this problem.

We simply need to evaluate the XPath expression "//*[@id = 'id-value']" (For those who are not familiar with XPath, this expression denotes all the nodes with value of id attribute='id-value'.
public static Element getElementById(Node doc, String id)
    {
        try {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//*[@id = '" + id + "']");
            Element result = (Element) expr.evaluate(doc, XPathConstants.NODE);
            return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            return null;
        }
    }

If you like to learn how to write an XML Schema(XSD), try this tutorial, and you can learn how to use the Java XML Validation API here.

Popular posts from this blog

Store your 450GB data on an A4 size paper: THE RAINBOW TECHNOLOGY

Software Development Models