我有这个 XML
<Parent>
<Children>
<child1>1</child1>
<secondchild>2</secondchild>
<child3>3</child3>
<fourth>4</fourth>
</Children>
</Parent>
使用 xpath,我想让每个Children
节点的名称以:
- 孩子1
- 次要
- 孩子3
- 第四
类似Parent/Children/*[@name]
.. 不针对任何属性,只有主子节点名称
也许是这样:
<?php
$string = '<Parent>
<Children>
<child1>1</child1>
<secondchild>2</secondchild>
<child3>3</child3>
<fourth>4</fourth>
</Children>
</Parent>';
$xml = new SimpleXMLElement($string);
$children = $xml->xpath('/Parent/Children/*');
foreach ($children as $child){
echo $child->getName() . "\n";
}
或者
<?php
$string = '<Parent>
<Children>
<child1>1</child1>
<secondchild>2</secondchild>
<child3>3</child3>
<fourth>4</fourth>
</Children>
</Parent>';
$xml = new SimpleXMLElement($string);
$children = $xml->xpath('/Parent/Children/*');
$result = array();
foreach ($children as $child){
$result[] = $child->getName();
}
print_r($result);
试试这个 XPATH:
Parent/Children/*/name()
这会在结果节点上调用 name() 函数。