Osa
Osa

Reputation: 1990

XML get nodes name through xPath

I have this XML

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

using xpath, i want to get each Children's node name to end up with :

something like Parent/Children/*[@name] .. without aiming at any attribute, only the main child node name

Upvotes: 1

Views: 4014

Answers (2)

sebastian_oe
sebastian_oe

Reputation: 7320

Try this XPATH:

Parent/Children/*/name()

This calls the name() function on the resulting nodes.

Upvotes: 0

Zemistr
Zemistr

Reputation: 1049

Maybe this:

<?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";
}

or

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

Upvotes: 3

Related Questions