1

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.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Java.net
  • 157
  • 2
  • 3
  • 13

4 Answers4

1

Use XPath to extract attribute values and element content.

    DocumentBuilder builder = DocumentBuilderFactory
                                 .newInstance()
                                 .newDocumentBuilder();

    Document doc = builder.parse(...);

    XPath xp = XPathFactory
                  .newInstance()
                  .newXPath();

    String id = xp.evaluate("planes_for_sale/@id", doc);
    String num = xp.evaluate("planes_for_sale/@num", doc);
    String name = xp.evaluate("planes_for_sale/@name", doc);

    System.out.println("id: " + id);
    System.out.println("num: " + num);
    System.out.println("name: " + name);

Produces:

id: planeId
num: 1452
name: boing
forty-two
  • 12,204
  • 2
  • 26
  • 36
0

Try with marshaling and unmarshalling mechanism

JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    EmployeeMap empMap = (EmployeeMap) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );

https://howtodoinjava.com/jaxb/jaxb-example-marshalling-and-unmarshalling-hashmap-in-java/

Mahender Ambala
  • 363
  • 3
  • 18
  • thnx for your answer but in my case its not the same xml structure if you look at my xml example so this way i think will not be the right one. – Java.net Oct 15 '18 at 19:29
0

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"));
                    }
                 }
Java.net
  • 157
  • 2
  • 3
  • 13
0

Look at this answer How to read XML using XPath in Java

It shows you how to

  • Read in an XML file to a DOM
  • Filter out a set of Nodes with XPath
  • Perform a certain action on each of the extracted Nodes.

A Variant with XPath 2.0 support can be found here

How to match string that ends with a number using XPath

jschnasse
  • 8,526
  • 6
  • 32
  • 72