【问题标题】:Java XML Parser to return all tags at the same levelJava XML Parser 返回同一级别的所有标签
【发布时间】:2020-07-22 04:39:14
【问题描述】:

我正在尝试做的事情的 TLDR:

  • 使用 xml 文档来存储类的表示。

  • 使用一些解析器类来递归文件并实例化这些类的实例。

  • 我目前在获取 nodeList 的子元素(而不是孙子元素)时遇到问题。

提前致谢。

假设我有以下 xml 文档

====== data.xml ======
<document>
    <tag>
        <child1> some content here </child1>
        <child2> some other content </child2>
    </tag>

    <tag>
        <child1> interesting content here </child1>
        <child2>
            <tag>
                <child1> a b c d </child1>
                <child2> e f g h </child2>
            </tag>
        </child2>
    </tag>
</document>

我尝试使用 xFile 解析器来获取所有标记节点。但是,当我执行以下操作时:

public static void parseXML() {
    File file = new File("src//data//data.xml");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;

    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    Document doc = null;

    try {
        doc = documentBuilder.parse(file);
    } catch (SAXException | IOException e) {
        e.printStackTrace();
    }

    try {
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        XPathExpression expr = xPath.compile("//document//tag");

        NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(i);
            System.out.println(nodeList.item(i).getTextContent());
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

我得到以下输出:

0

         some content here 
         some other content 
    
1

         interesting content here 
        
            
                 a b c d 
                 e f g h 
            
        
    
2

                 a b c d 
                 e f g h 

如何让它只返回直接嵌套在&lt;document&gt; 中的&lt;tag&gt; 元素(因为提供给xPath.compile(String string); 的路径是//document//tag

【问题讨论】:

    标签: java xml parsing xpath


    【解决方案1】:

    回答你提出的具体问题 - 我会改变这个

        XPathExpression expr = xPath.compile("//document//tag");
    

    到这里

        XPathExpression expr = xPath.compile("/document/tag[1]/*");
    

    // 匹配所有子节点,根据您的结构,您没有任何子节点。

    【讨论】:

    • 谢谢,但不幸的是我仍然得到相同的输出。
    • 我误解了-如果您只想要顶级标签元素,请使用 XPathExpression expr = xPath.compile("/document/tag[1]/*"); (已编辑)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2016-09-30
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多