5

I have an xml file having data which looks like given below:

 ....
 <ems:MessageInformation>
        <ecs:MessageID>2147321820</ecs:MessageID>
        <ecs:MessageTimeStamp>2016-01-01T04:38:33</ecs:MessageTimeStamp>
        <ecs:SendingSystem>LD</ecs:SendingSystem>
        <ecs:ReceivingSystem>CH</ecs:ReceivingSystem>
        <ecs:ServicingFipsCountyCode>037</ecs:ServicingFipsCountyCode>
        <ecs:Environment>UGS-D8UACS02</ecs:Environment>
</ems:MessageInformation>
....

There are many other nodes also. All nodes have namespace like ecs,tns,ems etc. I am suing following code part to extract all node names without namespace.

 public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));

        NodeList nodeList = document.getElementsByTagName("*");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            //System.out.println(node.getNodeName());
            System.out.println(node.getLocalName());
        }
}

But when I execute this code, it's printing null for individual node. Can someone tell me what I am doing wrong here?

I read on internet and I came to know that node.getLocalName() will give node name without namespace. What is wrong then in my case?

3
  • look at this docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html Commented Mar 3, 2016 at 5:32
  • For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as Document.createElement(), this is always null Commented Mar 3, 2016 at 6:02
  • better check the node type first, and then use the method Commented Mar 3, 2016 at 6:03

1 Answer 1

7

You need to set the document builder factory to be namespace aware first. Then getLocalName() will start returning non-null values.

DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setNamespaceAware(true);   // <=== here
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
Sign up to request clarification or add additional context in comments.

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.