简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM