【问题标题】:How to reach specific child node using XPATH? [duplicate]如何使用 XPATH 到达特定的子节点? [复制]
【发布时间】:2018-05-18 10:38:23
【问题描述】:

我有一个 XML 文件,我正在尝试解析它以获取名为 Result 的标签。

使用 xpath name(//results/*)count(//results/*),我可以看到 results 有 10 个子节点,每个子节点都命名为 Result。但是,如果我使用以下任何 xpath,则不匹配:

  • //Result
  • /query/results/Result[1]
  • /query/results/Result

我没有返回任何Result 标签。但是我知道有10个。我可以通过/query/results获得results,所以我知道我正在连接到这个文件。如何生成到达每个Result 的 xpath?

XML 结构(缩写):

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="10" yahoo:created="2013-07-17T15:15:52Z" yahoo:lang="en-US">
    <diagnostics>
    </diagnostics> 
    <results>
        <Result id="11762112" xmlns="urn:yahoo:lcl">
            <Title>California Rollin' Sushi Bar</Title>
            <Address>274 Goodman St N</Address>
            <City>Rochester</City>
            <State>NY</State>
            <Phone>(585) 271-8990</Phone>
            <Latitude>43.158685</Latitude>
            <Longitude>-77.585197</Longitude>
            <Rating>
                <AverageRating>3</AverageRating>
                <TotalRatings>10</TotalRatings>
                <TotalReviews>10</TotalReviews>
                <LastReviewDate>1341259499</LastReviewDate>
                <LastReviewIntro> I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?</LastReviewIntro>
            </Rating>
            <Distance>1.57</Distance>
            <Url>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</Url>
            <ClickUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester</ClickUrl>
            <MapUrl>http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map</MapUrl>
            <BusinessUrl>http://californiarollin.com/</BusinessUrl>
            <BusinessClickUrl>http://californiarollin.com/</BusinessClickUrl>
            <Categories>
                <Category id="96926236">Restaurants</Category>
                <Category id="96926205">Sushi Restaurants</Category>
            </Categories>
        </Result>
    </results>
</query>

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

    我已经尝试过您的 xml 并且不得不关闭 results 标记,我认为这是您复制和粘贴一点 xml 的一部分。除此之外,一切正常。我添加了更多Result 标签来测试它并得到了预期的结果。看看吧:

    import java.io.FileInputStream;
    import java.io.IOException;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class TestXpath {
        public static void main(String[] args) throws IOException, SAXException, IOException, ParserConfigurationException, XPathExpressionException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document parse = builder.parse(new FileInputStream("test.xml"));
    
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("/query/results/Result[2]");
    
            NodeList nl = (NodeList)  expr.evaluate(parse, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                System.out.println(item.getNodeName());
                System.out.println(item.getTextContent());
            }
        }
    }
    

    输出:

    Result
    
                California  2 Rollin' Sushi Bar
                274 Goodman St N
                Rochester
                NY
                (585) 271-8990
                43.158685
                -77.585197
    
                    3
                    10
                    10
                    1341259499
                     I went with my two girls last week and was told it would be around 1-1/2 wait so we had our name put on list hoping we would get seated sooner. It was busy because the groupons were expiring (which they knew ahead of time, so one would think they would be prepared). Well needless to say after 1-1/2 we still were not seated and there were several tables available. I asked how much longer and the hostess said another hour. I told her we have already been waiting for 1 hour she smirked and said sorry. People were coming in after us and being seated which made one of my girls ask the question why do they get a table before us. I went back in and said since my kids are tired is there anyway I could order take out and use my groupon since I am here and of course the hostess replied no its for dine in only. Ugh we left and ate elsewhere. I did call to speak with the manager who really was more concerned about telling me how proud she was of her staff and really didnt seem to care about our awful experience. Too bad because they lost several customers that night. What ever happend to customer service?
    
                1.57
                http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
                http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester
                http://local.yahoo.com/info-11762112-california-rollin-sushi-bar-rochester?viewtype=map
                http://californiarollin.com/
                http://californiarollin.com/
    
                    Restaurants
                    Sushi Restaurants
    

    注意 California 2 表示它是第二个 Result 条目。

    我也试过//Result/query/results/Result

    你手头的xml有什么问题吗?你能用我发布的代码试试吗?干杯!

    【讨论】:

    • 谢谢!除了忘记关闭results 标记之外,XML 没有任何问题。我也评论了上面的答案
    【解决方案2】:

    元素结果属于默认命名空间“urn:yahoo:lcl”。查看问题的答案:

    Getting elements with default namespace (no namespace prefix) using XPath

    【讨论】:

    • 好的,太好了!我不太明白这一点,但我看到//[local-name()="Result"] 让我得到了结果标签。我怎么可能只得到一个结果标签呢?
    • 更正://*[local-name()="Result"]
    • //*[local-name()="Result" and namespace-uri()='urn:yahoo:lcl'][1]
    • 如果我回答了你的问题,请接受答案。
    猜你喜欢
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    相关资源
    最近更新 更多