Twistleton
Twistleton

Reputation: 2935

Parsing XML with DocumentBuilder and read the value

I want parse this XML file with Java's DocumentBuilder:

 <GLS version="1" type="telegram">
   <telegram version="1">
       <params>
           <id_batch>60500.012.16"</id_batch>
           <supplier value="HUGO"/>
       </params>
   </telegram>
 </GLS>

Read the id_batch tag is no problem, but now can I the value of the supplier tag?

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;


DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);

doc.getDocumentElement().normalize();

System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("params");

for (int i = 0; i < nList.getLength(); i++) {
         Node nNode = nList.item(i);

         System.out.println("\nCurrent Element: " + nNode.getNodeName());

         if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;
            System.out.println("-1-> " + eElement.getElementsByTagName("id_batch").item(0).getTextContent());
            System.out.println("-2-> " + eElement.getElementsByTagName("supplier").item(0).getAttribute("value"));

             }
        }

This error arise: Cannot resolve method 'getAttribute(java.lang.String)'

Something I'm doing wrong! But what?

Thanks

Upvotes: 1

Views: 2388

Answers (2)

Jason
Jason

Reputation: 56

Using your own example, you just need to call getAttribute(..). So add the following:

System.out.println("-3-> " + eElement.getElementsByTagName("supplier").item(0).getAttribute("value"));

Upvotes: 3

value="HUGO" is an attribute of the getElementsByTagName supplier... so you are trying to get that wrongly...

Try instead:

System.out.println("value : " + eElement.getAttribute("supplier").getAttribute("value"));

Upvotes: 1

Related Questions