Skip to content
Advertisement

Read few xml elements only in an efficient way

I want to read only few XML tag values .I have written the below code.XML is big and a bit complex. But for example I have simplified the xml . Is there any other efficient way to solve it ?I am using JAVA 8

DocumentBuilderFactory dbfaFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = dbfaFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse("xml_val.xml");
        
        
        System.out.println(doc.getElementsByTagName("date_added").item(0).getTextContent());



<item_list id="item_list01">
   <numitems_intial>5</numitems_intial>
   <item>
     <date_added>1/1/2014</date_added>
     <added_by person="person01" />
   </item>
   <item>
      <date_added>1/6/2014</date_added>
      <added_by person="person05" />
    </item>
    <numitems_current>7</numitems_current>
    <manager person="person48" />
</item_list>

Advertisement

Answer

Using XPAth and passing a specific expression to get the desired element

public class MainJaxbXpath {

    public static void main(String[] args) {
        try {
            FileInputStream fileIS;
            fileIS = new FileInputStream("/home/luis/tmp/test.xml");

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

            Document xmlDocument;
            xmlDocument = builder.parse(fileIS);

            XPath xPath = XPathFactory.newInstance().newXPath();
            String expression = "//item_list[@id="item_list01"]//date_added[1]";
            String nodeList =(String) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.STRING);
            System.out.println(nodeList);
        } catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e3) {
            e3.printStackTrace();
        }

    }

}

Result:

1/1/2014

To look for more than one element on the same operation

        String expression01 = "//item_list[@id="item_list01"]//date_added[1]";
        String expression02 = "//item_list[@id="item_list02"]//date_added[2]";
        String expression = String.format("%s | %s", expression01, expression02);
        NodeList nodeList =(NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                System.out.println(currentNode.getTextContent());
            }
        }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement