xml Xpath:选择直接子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8981091/
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-09-06 15:07:11  来源:igfitidea点击:

Xpath: Select Direct Child Elements

xmlxpath

提问by Nic Hubbard

I have an XML Document like the following:

我有一个如下的 XML 文档:

<parent>
<child1>
  <data1>some data</data1>
</child1>
<child2>
  <data2>some data</data2>
</child2>
<child3>
  <data3>some data</data3>
</child3>
</parent>

I would like to be able to get the direct children of parent (or the element I specify) so that I would have child1, child2 and child3 nodes.

我希望能够获得父级(或我指定的元素)的直接子级,以便我拥有 child1、child2 和 child3 节点。

Possible?

可能的?

回答by Dimitre Novatchev

Or even:

甚至:

/*/*

this selects all element - children of the top element (in your case named parent) of the XML document.

这将选择所有元素 - parentXML 文档的顶部元素(在您的示例中名为)的子元素。

XSLT - based verification:

基于 XSLT 的验证

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
  <xsl:copy-of select="/*/*"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

当此转换应用于提供的 XML 文档时

<parent>
    <child1>
        <data1>some data</data1>
    </child1>
    <child2>
        <data2>some data</data2>
    </child2>
    <child3>
        <data3>some data</data3>
    </child3>
</parent>

the XPath expression is evaluated and the selected nodes are output:

计算 XPath 表达式并输出所选节点

<child1>
   <data1>some data</data1>
</child1>
<child2>
   <data2>some data</data2>
</child2>
<child3>
   <data3>some data</data3>
</child3>

回答by Phil

This should select all child elements of <parent>

这应该选择的所有子元素 <parent>

/parent/*


PHP Example

PHP 示例

$xml = <<<_XML
<parent>
  <child1>
    <data1>some data</data1>
  </child1>
  <child2>
    <data2>some data</data2>
  </child2>
  <child3>
    <data3>some data</data3>
  </child3>
</parent>
_XML;

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath = new DOMXPath($doc);
$children = $xpath->query('/parent/*');
foreach ($children as $child) {
    echo $child->nodeName, PHP_EOL;
}

Produces

生产

child1
child2
child3