简体   繁体   English

Java XPath获取具有与特定文本匹配的特定标记的所有节点

[英]Java XPath get all nodes with specific tag matching specific text

I have the following regular XML file: 我有以下常规XML文件:

<root>
    <Items>
        <Item>
            <tag1>text1</tag1>
            <tag2>text2</tag2>
            <tag3>text3</tag3>
        </Item>
        <Item>
            <tag1>text1</tag1>
            <tag2>text4</tag2>
            <tag3>text5</tag3>
        </Item>
    </Items>
</root>

And I want to get all nodes (all <Item> ) where <tag1> text equals to text1 , and then print their all other tags for example <tag2> . 我想得到所有节点(所有<Item> ),其中<tag1> text等于text1 ,然后打印所有其他标签,例如<tag2>

I started with this but struggling to find answers to the TODO'S: 我从这开始,但努力寻找TODO'S的答案:

try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(("\URI\file.xml"));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    //TODO: Is this correct query?
    XPathExpression expr = xpath.compile("//root//Items//Item//tag1[contains(., 'text1')]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i=0; i<nl.getLength(); i++) {
        //TODO: How to iterate over all matched <Item> and get their <tag2>, <tag3> etc.?
    }
} catch (Exception e) {e.printStackTrace();}

Thanks, 谢谢,

You can use Chrome Developer Tools $x("path") function for testing XPaths. 您可以使用Chrome开发者工具$x("path")功能来测试XPath。 It's really easy. 这真的很容易。 It works on latest Firefox too. 它也适用于最新的Firefox。

I made an HTML file with your supplied text and opened it in Chrome. 我使用您提供的文本制作了一个HTML文件,然后在Chrome中打开它。 In console, type $x("/some-path") to test stuff. 在控制台中,键入$x("/some-path")来测试内容。

  1. Get items: 获取物品:

     //Item 
  2. Where tag1 text equals text1: 其中tag1文本等于text1:

     //Item/tag1[.='text1'] 
  3. Get following sibling that is a tag2: 获取以下作为tag2的兄弟:

     //Item/tag1[.='text1']/following-sibling::tag2 

If you want the Item and not the tag2: 如果你想要Item而不是tag2:

//Item[ ./tag1[.='text1']/following-sibling::tag2 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM