3

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?

1
  • Many thanks. This is the response. Can you answer to mark it as aswered? (Sorry for my English) Commented Jul 11, 2016 at 16:28

3 Answers 3

5

A - Demo Code

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GetXMLNodeInJavaDemo {

    public static void main(String[] args) {

        try {
            File fXmlFile = new File("sampleFile.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

            dbFactory.setNamespaceAware(true);

            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize();

            printByElementTagname(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printByElementTagname(Document doc) {
        NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("*", "UBLExtension");
        Node node;
        for(int i = 0; i < nodes.getLength(); i++) {
            node = nodes.item(i);
            System.out.println(node.getNodeName() + " : " + node.getTextContent().trim());
        }
    }

}

B - Sample File : sampleFile.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
            </ext:ExtensionContent>
        </ext:UBLExtension>
        <ext:UBLExtension>
            <ext:ExtensionContent>
                What you want
            </ext:ExtensionContent>
        </ext:UBLExtension>
    </ext:UBLExtensions>
</Invoice>

C - Sample Output

ext:UBLExtension : Some Code
ext:UBLExtension : What you want
Sign up to request clarification or add additional context in comments.

4 Comments

@Giancarlo Ventura Granados Well I'll be happier if it really helps, you can give an upvote for it :)
I still can not upvote your response, I only have 13 rep points
@Giancarlo Ventura Not a problem, I didn't know there's such a mechanism I'm sorry. Welcome to the stack overflow :)
@Giancarlo Ventura Granados I've noticed :D
2

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");

2 Comments

Many thanks, this is the response. I still can not give you points , but I have marked as correct.
It is also better to actually specify the namespace, rather than using wildcard. Define a static final String constant, e.g. EXT_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2", and use it in place of "*".
1

You can try to work with xpath

public static NodeList getNodesWithXPath(Node aNode, String aXPath) {
    try {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression xPathExpression = xpath.compile(aXPath);
        return (NodeList) xPathExpression.evaluate(aNode, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // ignore
    } catch (NullPointerException e) {
        // ignore
    }
    return null;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.