I have this XML document:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<Achild>
.....
</Achild>
</RootElement>
How can I check if the document contains Achild element or not? I tried
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
try {
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(configFile);
final Node parentNode = doc.getDocumentElement();
final Element childElement = (Element) parentNode.getFirstChild();
if(childElement.getNodeName().equalsIgnoreCase(...
but it gives me an error (childElement is null).
I think that you’re getting
#textnode (that between<RootElement>and<Achild>) as first child (that’s pretty common mistake), for example:Returns:
Use instead:
Wanted result:
EDIT:
There is second way using
DocumentBuilderFactory.setIgnoringElementContentWhitespacemethod:However this works only in validating mode, so you need to provide DTD in your XML document:
and set
factory.setValidating(true). Full example:Wanted result with original code: