XML通过xPath获取节点名称

时间:2012-12-14 00:31:06

标签: php xml xpath

我有这个XML

<Parent>
 <Children>
  <child1>1</child1>
  <secondchild>2</secondchild>
  <child3>3</child3>
  <fourth>4</fourth>
 </Children>
</Parent>

使用xpath,我想让每个Children的节点名称最终得到:

  • child1
  • secondhild
  • child3
  • 第四
Parent/Children/*[@name]之类的东西 ..没有瞄准任何属性,只有主子节点名称

2 个答案:

答案 0 :(得分:2)

也许这个:

<?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);

答案 1 :(得分:0)

试试这个XPATH:

Parent/Children/*/name()

这会在结果节点上调用name()函数。