在php中按属性选择xml节点
问题描述:
如何在不遍历每个子对象和每个属性/值的情况下,通过了解属性值来查找节点值?
How do I find the node value by knowing the attribute value without traversing through every child and every attribute/value ?
$dom = new DOMDocument;
$dom->load('test.xml');
$rows = $dom->getElementsByTagName('row');
foreach ($rows as $row) {
$header = VALUE OF <field name="header">
$text = VALUE OF <field name="text">
}
XML:
<resultset>
<row>
<field name="item">2424</field>
<field name="header">blah blah 1</field>
<field name="text" xsi:nil="true" />
...
</row>
<row>
<field name="item">5321</field>
<field name="header">blah blah 2</field>
<field name="text">some text</field>
...
</row>
</resultset>
答
最简单的方法是使用 DOMXPath::query
docs
The simplest thing to do is use DOMXPath::query
docs
以下代码查找<row>
节点内具有名称属性等于"header"的所有<field>
节点:
The following code finds all the <field>
nodes within <row>
nodes that have a name attribute equal to "header":
$dom = new DOMDocument;
$dom->loadXML($str); // where $str is a string containing your sample xml
$xpath = new DOMXPath($dom);
$query = "//row/field[@name='header']";
$elements = $xpath->query($query);
foreach ($elements as $field) {
echo $field->nodeValue, PHP_EOL;
}
使用您提供的示例xml,以上输出:
Using the sample xml you provide, the above outputs:
blah blah 1
blah blah 2