使用 PHP 进行 XPath 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/230592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:00:00  来源:igfitidea点击:

XPath query with PHP

phpxmlxpath

提问by liewl

Here's the XML code I'm working with:

这是我正在使用的 XML 代码:

<inventory>
    <drink>
        <lemonade supplier="mother" id="1">
            <price>.50</price>
            <amount>20</amount>
        </lemonade>
        <lemonade supplier="mike" id="4">
            <price>.00</price>
            <amount>20</amount>
        </lemonade>
        <pop supplier="store" id="2">
            <price>.50</price>
            <amount>10</amount>
        </pop>
    </drink>
</inventory>

Then I wrote a simple code to practice working with XPath:

然后我写了一个简单的代码来练习使用 XPath:

<?php
    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');

    $xpathvar = new Domxpath($xmldoc);

    $queryResult = $xpathvar->query('//lemonade/price');
    foreach($queryResult as $result) {
        echo $result->textContent;
    }
?>

That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like

该代码运行良好,按预期输出所有柠檬水价格值。现在,当我更改查询字符串以仅选择属性设置为特定值的元素时,例如

//lemonade[supplier="mother"]/price

//柠檬水[supplier="mother"]/价格

or

或者

//lemonade[id="1"]/price

//柠檬水[id="1"]/价格

it won't work, no output at all. What am i doing wrong?

它不会工作,根本没有输出。我究竟做错了什么?

回答by bobwienholt

Try this:

尝试这个:

//lemonade[@id="1"]/price

or

或者

//lemonade[@supplier="mother"]/price

Without the "@" it looks for child elements with that name instead of attributes.

如果没有“@”,它会查找具有该名称而不是属性的子元素。

回答by Tirno

This is only tangentially related, but when you use XPath on a document for which you know the structure, don'tuse "//some-element-name". It's very nice for a quick example, but when you hit a huge xml file with that query, particularly if it is followed by something complex, you will quickly run into performance issues.

这只是切线相关,但是当您在知道其结构的文档上使用 XPath 时,不要使用“//some-element-name”。作为一个简单的例子,这非常好,但是当您使用该查询访问一个巨大的 xml 文件时,特别是如果它后面跟着一些复杂的东西,您将很快遇到性能问题。

inventory/drink/lemonade[@supplier="mother"]/price

库存/饮料/柠檬水[@supplier="mother"]/价格

回答by Kris

you have to use the @ sign to indicate attribute within the predicate like so: //lemonade[@supplier="mother"]/price, that's all.

您必须使用 @ 符号来指示谓词中的属性,如下所示://lemonade[@supplier="mother"]/price,仅此而已。