使用XPATH列出没有内容的XML子元素名称

时间:2022-06-12 09:46:44

Consider this simple XML schema:

考虑这个简单的XML模式:

<products>
    <category name="furniture">
        <item name="chair">
            <size>
                <small>10</small>
                ...and many more
                <large>20</large>
            </size>
        </item>
    </category>
</products>

I'm looking to list the child elements of <size> without their actual content using XPATH.

我想使用XPATH列出 的子元素,而没有实际内容。

$xml=simple_load_file('file.xml');

foreach ($xml->xpath("products/category[@=name'furniture']/item[@name='chair]/size") as $size)
     echo $size->????? . '<br>';

$size->children(); outputs the actual text as such:

$大小 - >儿童();输出实际文本:

10
20

I'm looking for the following output:

我正在寻找以下输出:

small
...rest of elements
large

1 个解决方案

#1


0  

You have some errors in you Xpath expression. The first = is in the wrong position and the chair string is missing the closing quote. Adding /* You can select the child nodes of size directly.

您的Xpath表达式中有一些错误。第一个=处于错误的位置,主席字符串缺少结束报价。添加/ *您可以直接选择大小的子节点。

/products/category[@name='furniture']/item[@name='chair']/size/*

Full source using DOMDocument:

使用DOMDocument的完整源代码:

$xml = <<<'XML'
  <products>
    <category name="furniture">
        <item name="chair">
            <size>
                <small>10</small>
                <large>20</large>
            </size>
        </item>
    </category>
  </products>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);

$nodes = $xpath->evaluate("/products/category[@name='furniture']/item[@name='chair']/size/*");

foreach ($nodes as $node) {
  echo $node->localName, "\n";
}

#1


0  

You have some errors in you Xpath expression. The first = is in the wrong position and the chair string is missing the closing quote. Adding /* You can select the child nodes of size directly.

您的Xpath表达式中有一些错误。第一个=处于错误的位置,主席字符串缺少结束报价。添加/ *您可以直接选择大小的子节点。

/products/category[@name='furniture']/item[@name='chair']/size/*

Full source using DOMDocument:

使用DOMDocument的完整源代码:

$xml = <<<'XML'
  <products>
    <category name="furniture">
        <item name="chair">
            <size>
                <small>10</small>
                <large>20</large>
            </size>
        </item>
    </category>
  </products>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);

$nodes = $xpath->evaluate("/products/category[@name='furniture']/item[@name='chair']/size/*");

foreach ($nodes as $node) {
  echo $node->localName, "\n";
}