Alexander Demerdzhiev
Alexander Demerdzhiev

Reputation: 1044

DOM XML child nodes

If i have an XML for example like this:

  <?xml version="1.0" encoding="utf-8" ?> 
  <parent >
     <child>
         <grandchild>
         </grandchild>
     </child> 
  </parent>

And i want to get all the children of the parent node (using php for example), when i call

$xmlDoc->loadXML('..');

$rootNode = $xmlDoc->documentElement;

$children = $rootNode->childNodes;

what would $children contain? Will it contain only <child> node ot will it contain <child> and <grandchild> both?

Upvotes: 2

Views: 2271

Answers (1)

ThW
ThW

Reputation: 19502

The parent document element node has 3 child nodes. The element node child and two text nodes containing the whitespaces before and after the node:

$document = new DOMDocument();
$document->loadXml($xml);
foreach ($document->documentElement->childNodes as $childNode) {
  var_dump(get_class($childNode));
}

Output:

string(7) "DOMText"
string(10) "DOMElement"
string(7) "DOMText"

If you disable the preserve white space option on the document, it will remove the whitespace nodes while loading the xml.

$document = new DOMDocument();
$document->preserveWhiteSpace = FALSE;
$document->loadXml($xml);
...

Output:

string(10) "DOMElement"

To get nodes in a more flexible way use Xpath. It allows you to use expressions to fetch nodes:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('/*/child|/*/child/grandchild') as $childNode) {
  var_dump(get_class($childNode), $childNode->localName);
}

Output:

string(10) "DOMElement"
string(5) "child"
string(10) "DOMElement"
string(10) "grandchild"

Upvotes: 2

Related Questions