2012-12-14 104 views
1

我使用XPath有這個XMLXML得到節點名通過XPATH

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

,我想每個Children的節點直到結束:

  • child1
  • secondhild
  • child3
  • fourth

Parent/Children/*[@name] ..沒有,只有主子節點名稱

回答

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

試試這個XPATH:

Parent/Children/*/name() 

這將調用結果節點上的name()函數。

+0

不工作,但是,Zemistr的答案運作良好,謝謝 – Osa