Giancarlo Ventura Granados Giancarlo Ventura Granados - 4 months ago 39
Java Question

Get XML node with namespace in java

I have the next XML:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:ccts="urn:un:unece:uncefact:documentation:2"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
xmlns:qdt="urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2"
xmlns:sac="urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1"
xmlns:udt="urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ext:UBLExtensions>
<ext:UBLExtension>
<ext:ExtensionContent>
<!-- SOME CODE HERE -->
</ext:ExtensionContent>
</ext:UBLExtension>
<ext:UBLExtension>
<ext:ExtensionContent>
<!-- I WANT TO GET THIS NODE -->
</ext:ExtensionContent>
</ext:UBLExtension>
</ext:UBLExtensions>


How can I get this node? I've tried

Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(PATH_TO_MY_XML));
NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("*", "UBLExtension");


but it returns an empty array. How can I do it?

Answer

You need to make sure the XML parser is namespace aware.

You should also make sure to close the FileInputStream, preferably using try-with-resources.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);

Document doc;
try (InputStream xmlStream = new FileInputStream(PATH_TO_MY_XML)) {
    doc = dbf.newDocumentBuilder().parse(xmlStream);
}
NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("*", "UBLExtension");
Comments