仅以有效的方式读取少量 xml 元素 [英] Read few xml elements only in an efficient way

查看:31
本文介绍了仅以有效的方式读取少量 xml 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想读取几个 XML 标记值.我编写了以下代码.XML 很大而且有点复杂.但是例如我已经简化了 xml .有没有其他有效的方法来解决它?我正在使用 JAVA 8

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>

推荐答案

使用 XPAth 并传递特定表达式以获得所需元素

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();
        }

    }

}

结果:

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());
            }
        }

这篇关于仅以有效的方式读取少量 xml 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆