Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java XML解析器返回同一级别的所有标记_Java_Xml_Parsing_Xpath - Fatal编程技术网

Java XML解析器返回同一级别的所有标记

Java XML解析器返回同一级别的所有标记,java,xml,parsing,xpath,Java,Xml,Parsing,Xpath,我要做的事情的TLDR: 使用xml文档存储类的表示形式 使用一些解析器类递归文件并实例化这些类的实例 我目前在获取节点列表的子元素(而不是孙子)时遇到问题 提前谢谢 假设我有以下xml文档 ====== data.xml ====== <document> <tag> <child1> some content here </child1> <child2> some other co

我要做的事情的TLDR:

  • 使用xml文档存储类的表示形式

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

  • 我目前在获取节点列表的子元素(而不是孙子)时遇到问题

提前谢谢

假设我有以下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>

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

来回答您提出的特定问题-我将更改此选项

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

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

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

谢谢,但不幸的是,我仍然得到相同的输出。我误解了-如果您只需要顶级标记元素,请使用XPathExpression expr=xPath.compile(“/document/tag[1]/*”);(已编辑)
    XPathExpression expr = xPath.compile("//document//tag");
    XPathExpression expr = xPath.compile("/document/tag[1]/*");