1

我有这个 XML

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

使用 xpath,我想让每个Children节点的名称以:

  • 孩子1
  • 次要
  • 孩子3
  • 第四

类似Parent/Children/*[@name] .. 不针对任何属性,只有主子节点名称

4

2 回答 2

3

也许是这样:

<?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);
于 2012-12-14T00:46:17.933 回答
0

试试这个 XPATH:

Parent/Children/*/name()

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

于 2012-12-14T00:49:51.623 回答