1

I have the following xml snippet from which I am trying to retrieve the first element using JDOM but I am getting nullpointer exception.please help me out if any one knows.

<db1:customer xmlns:db1="http://www.project1.com/db1">
<db1:customerId>22</db1:customerId>
<db1:customerName>PRASAD44</db1:customerName>
<db1:address>Chennai</db1:address>
<db1:email>pkk@gmail.com</db1:email>
<db1:lastUpdate>2014-08-01T00:00:00+05:30</db1:lastUpdate>
<db1:nameDetail>BSM_RESTeter</db1:nameDetail>
<db1:phoneBiz>9916347942</db1:phoneBiz>
<db1:phoneHome>9916347942</db1:phoneHome>
<db1:phoneMobile>944990031</db1:phoneMobile>
<db1:rating>22</db1:rating>
</db1:customer>

here is what I am doing,

    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("CommonFiles/file.xml");
    Document doc = (Document) builder.build(xmlFile);
    Element rootNode = doc.getRootElement();
    Element customerid = rootNode.getChild("sure:customerId");
    System.out.println("customerid ======"+customerid); 

The print statement displays null.

rolfl
  • 17,539
  • 7
  • 42
  • 76
Praveen
  • 201
  • 5
  • 18

1 Answers1

1

When dealing with XML containing namespaces, you need to use the Namespace instance that's appropriate for your document. In this case, you have:

<db1:customer xmlns:db1="http://www.project1.com/db1">

The namespace here is http://www.project1.com/db1 and the prefix is db1.

In JDOM you can creaate a reference to a namespace with:

Namespace db1 = Namespace.getNamespace("db1", "http://www.project1.com/db1");

Now, when you retrieve the content in your document, use:

Element customerid = rootNode.getChild("customerId", db1);

Note that you get content using the Namespace object, not the prefix for the element (there is no "db1:" prefix for the "customerId"

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Perfect.Thank you very much rolfl.I have one more question.After updating the xml file,I am getting the header {},which should not be available in the updated file.Is there a way to prevent this using JDom – Praveen Oct 28 '14 at 10:55
  • On your XMLOutputter, you can supply a Format, get a format with, for example `Format.getPrettyFormat()`, and then call `setOmitDeclaration(true)` on it: [see this](http://jdom.org/docs/apidocs/org/jdom2/output/Format.html#setOmitDeclaration(boolean)) – rolfl Oct 28 '14 at 11:01