Search code examples
javaxmljdom

How to get the value of attribute value from XML using JDOM


<ns2:VehicleStatusReport>
   <ns2:DataContent>
      <ns2:DataItem>
         <ns2:Name>star</ns2:Name>
         <ns2:Percent>65.6</ns2:Percent>
         <ns2:Source>egg</ns2:Source>
      </ns2:DataItem>

     <ns2:DataItem>
         <ns2:Name>position</ns2:Name>
         <ns2:Position>
            <ns3:RandomNumbers>8.378137,8.36</ns3:RandomNumbers>                       
            <ns3:Integer>124.9,124.999901</ns3:Integer>
            <ns3:Heading>0</ns3:Heading>          
         </ns2:Position>             
      </ns2:DataItem>

Above is sample XML that I'm trying to parse in java using JDOM, following is my code for the same.

String xml="above xml";
org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
Element rootNode = doc.getRootElement();
Element subRootNode = rootNode.getChild("ns2:DataContent");
Element subsubRootNode =  subRootNode.getChild("ns2:DataItem");
Element subsubsubRootNode = subsubRootNode.getChild("ns2:Position");
String value=subsubsubRootNode.getAttributeValue("ns3:RandomNumbers");
System.out.println(value);

But When I execute the above code I get NULLPOINTEREXCEPTION at follwing line

Element subsubRootNode =  subRootNode.getChild("ns2:DataItem");

How to get the value of RandomNumbers and Interger xml tags? Thanks !!!!


Solution

  • To access elements that are in a namespace in JDOM, you should use the method getChild(localName, namespaceUri).

    For example if the element is

    <ns:donald xmlns:ns="http://us.nepotism.com/">
      <ns:ivanka/>
    </ns:donald>
    

    then you should use getChild("ivanka", "http://us.nepotism.com/")

    The answer from @GalDraiman appears to ignore the namespace issue completely.