我有一个如下所示的XML文档:
<parent>
<child1>
<data1>some data</data1>
</child1>
<child2>
<data2>some data</data2>
</child2>
<child3>
<data3>some data</data3>
</child3>
</parent>
我希望能够获取父元素(或我指定的元素)的直接子元素,这样我将拥有child1、child2和child3节点。
可以吗?
/*/*
这选择了XML文档中顶层元素(在您的情况下命名为parent
)的所有元素子节点。
基于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>
当应用此转换到提供的 XML 文档时:
<parent>
<child1>
<data1>some data</data1>
</child1>
<child2>
<data2>some data</data2>
</child2>
<child3>
<data3>some data</data3>
</child3>
</parent>
评估XPath表达式并输出所选节点:
<child1>
<data1>some data</data1>
</child1>
<child2>
<data2>some data</data2>
</child2>
<child3>
<data3>some data</data3>
</child3>
<parent>
的所有子元素。/parent/*
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;
}
产生
child1
child2
child3
DOMDocument
和DOMXpath
可以正常工作。那是你实际使用的XML吗? - Phil
child
可能会有所帮助。 - shellbye