Search code examples
javadomsaxxerces

Xerces JAR causing exception


Facing a strange issue with Xerces jars. I migrated my code into a different workspace. There was a portion of the code that used org.w3c.dom XML classes. Now that i migrated the code, the same code is throwing exceptions.

import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

But when i debug it the objects created are of type:

org.apache.xerces.jaxp.DocumentBuilderFactoryImpl

Not sure where the xerces classes came into the picture. And this is causing the code to fail.

Updating with the code:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(new StringReader(xmlString));
Document document = builder.parse(inputSource);

String grade = "A";
NodeList nodes = document.getElementsByTagName("student");
if (!routeLimit.equals("")) {
    Text gradeText = document.createTextNode(grade);
    Element gradeTag = document.createElement("grade");
    gradeTag .appendChild(gradeText);
    nodes.item(0).appendChild(gradeTag);
} 

The line: nodes.item(0).appendChild(gradeTag);

Throws a null pointer exception.

Also, when i debug the code, the value of the document variable [#document: null], I checked this site and saw many people facing the same issue. But there were very few concrete answers.


Solution

  • The issue was with the XML namespace.

    I had to set the:

    domFactory.setNamespaceAware(true);
    

    and then fetch the node using:

    NodeList nodes = document.getElementsByTagName("ml:student");
    

    Kind of stumbled upon the solution. the same code worked before, without the namespace.