0

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.

  • 1
    Does this answer your question? [Why getChild() method of JDOM returns null?](https://stackoverflow.com/questions/5259321/why-getchild-method-of-jdom-returns-null) – Abra Feb 01 '21 at 13:16
  • Call the **other** `getChild` method: [`getChild(java.lang.String cname, Namespace ns)`](http://www.jdom.org/docs/apidocs/org/jdom2/Element.html#getChild(java.lang.String,%20org.jdom2.Namespace)) – Andreas Feb 01 '21 at 13:16

1 Answers1

1

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));
ajayg2808
  • 375
  • 2
  • 10