midhunKRaj
midhunKRaj

Reputation: 1

How to access child element of XML in Java using org.jdom.Element

I am completely new to XML based REST operations. I have a XML file

<?xml version="1.0" encoding="UTF-8"?>
<BillOfLadingCoverLetter xmlns:cmp="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Bill Of Lading Cover Letter.xsd">
    <Header>
        <cmp:DocumentID>
            <cmp:RID>shipper</cmp:RID>
            <cmp:GeneralID>2</cmp:GeneralID>
            <cmp:Version>1</cmp:Version>
        </cmp:DocumentID>
        <cmp:DocType>
            <cmp:DocTypeCode>1111</cmp:DocTypeCode>
            <cmp:DocTypeDescription>COVER LETTER</cmp:DocTypeDescription>
        </cmp:DocType>
        <cmp:Status>FINAL</cmp:Status>
    </Header>
    <Body/>
</BillOfLadingCoverLetter>

I want to access and get all the fields in this XML

import org.jdom.Element;

Element jdomRoot = doc.getRootElement();

 //2 jdomRoot.getChild("Header").getChild("cmp:DocumentID");
 1 jdomRoot.getChild("Header").getChild("DocumentID");

both 1 and 2 is returning null. But jdomRoot.getChild("Header") is returning value.

Please help me how to access the values in the XML.

Upvotes: 0

Views: 1193

Answers (1)

ajayg2808
ajayg2808

Reputation: 375

Add namespace to xml file. use it in program.

XML:

Updated XML

Code:

SAXBuilder builder = new SAXBuilder();
FileInputStream in = new FileInputStream(xmlFile);
Document doc = builder.build(in);

Element root = doc.getRootElement();
Namespace xmlNamespace = root.getNamespace();
Element headerEle = root.getChild("Header",xmlNamespace);
Element docIDEle = headerEle.getChild("DocumentID", xmlNamespace);
System.out.println(docIDEle.getChildText("RID", xmlNamespace));

Upvotes: 1

Related Questions