I have tried all possible answers on Stackoverflow but I can't get this resolved.
I have the following xml as a String:
private static final String xmlStr = "<parameters>\n" +
" <parameter>\n" +
" <name>emp</name>\n" +
" <keyvalue>John Smith</keyvalue>\n" +
" </parameter>\n" +
" <parameter>\n" +
" <name>age</name>\n" +
" <keyvalue>22</keyvalue>\n" +
" </parameter>\n" +
" <parameter>\n" +
" <name>Birth Date</name>\n" +
" <keyvalue>02/05/1978</keyvalue>\n" +
" </parameter>\n" +
" <parameter>\n" +
" <name>password</name>\n" +
" <keyvalue>ye63633</keyvalue>\n" +
" </parameter>\n" +
"</parameters>";
The parameters can be replaced with any string (which I tried without sucess), and the following code returns null document:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
I have tried replacing document with:
Document document = builder.parse(new InputSource(new StringReader(xmlStr)));//This used to work 2 weeks ago.
document is returning null document all the time and I can't figure out what I am doing wrong. The same code used to work few weeks ago.
I am using Java 1.8 !!
I appericiate your help.
UPDATE:
Here is the full code that takes the above xmlStr and try to access age of the employee.
private String getElementValue(String tagName, String xmlString) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
Element rootElement = document.getDocumentElement();
NodeList list = rootElement.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Based on the comments, the document is not null at all but there is an issue accessing the desired xml tag. So the code NodeList list = rootElement.getElementsByTagName("age");
has size 0. i.e its not entering the loop at all.
document.toString()?toString()result that contains the text "null", but that's definitely not an error. Have you tried actually using the document? Note that the debugger is showing 39 nodes...