javaxmljdom

How to parse an XML element root an select some values of it in Java?


I am looking for a practical way to parse an xml root element an get some values from it. I have tried many ways, but none of them are efficient.

       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

                Document doc = factory.newDocumentBuilder().parse(fileLoaded);

                Element root = null;

                NodeList list = doc.getChildNodes();
               System.out.println(list.toString());
                for (int i = 0; i < list.getLength(); i++) {
                  if (list.item(i) instanceof Element) {
                    root = (Element) list.item(i);
                    System.out.println(root.toString());
                    break;
                  }
                }
                root = doc.getDocumentElement();
              }

XML file:

    <planes_for_sale id="planeId" num="1452" name="boing">
    <ad>
      <year> 1977 </year>
      <make> test </make>
      <model> Skyhawk </model>
      <color> Light blue and white </color>
      <description> New paint, nearly new interior,
        685 hours SMOH, full IFR King avionics </description>
      <price> 23,495 </price>
      <seller phone = "555-222-3333"> Skyway Aircraft </seller>
      <location>
      <city> Rapid City, </city>
      <state> South Dakota </state>
  </location>

In my case I want to load id, num, name from planes_for_sale root element.


Solution

  • For anyone who is looking for a pratical way here is one tested :

        DocumentBuilderFactory factory = DocumentBuilderFactory
                        .newInstance();
    
                Document doc = factory.newDocumentBuilder().parse(fileLoaded);
                doc.getDocumentElement().normalize();
                System.out.println("Root element :"
                        + doc.getDocumentElement().getNodeName());
                NodeList nList = doc.getElementsByTagName("planes_for_sale");
    
                  System.out.println("----------------------------");
    
                     for (int temp = 0; temp < nList.getLength(); temp++) {
                        Node nNode = nList.item(temp);
                        System.out.println("\nCurrent Element :" + nNode.getNodeName());
                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element eElement = (Element) nNode;
                            System.out.println("Plane name : " 
                               + eElement.getAttribute("name"));
                        }
                     }