Only one nodename, but multiple values for nodeValue- DOMXPATH

167 Views Asked by At

Why nodename prints "root", but nodeValue returns multiple and all the values in child nodes.

Running this code, the echo will return

"The Name of the parent node is root Its value is Text value 11111 Empty text value 2222 space text value 3333 "

The second echo will return this

"The child node is spaceIts value is space text value 3333"

<?php

$xmldoc=
    '<?xml version="1.0" ?><root>

<text>Text value 11111</text>
<none/>
<empty>Empty text value 2222</empty>
<space>space text value 3333 </space>
</root>';

$domdoc = new DoMDocument();
$domdoc->loadXML($xmldoc);

$xpath = new DOMXPath($domdoc);

$rootNodeListParent = $xpath->query("//root");
$rootNodeParent = $rootNodeListParent[0];
echo "The Name of the parent node is " . $rootNodeParent->nodeName. " Its value is " . $rootNodeParent->nodeValue . "<br>";

$queryNodeList = $xpath->query("//space");
$nodeSpace = $queryNodeList[0];
 echo "The child node is " . $nodeSpace->nodeName. "Its value is " . $nodeSpace->nodeValue; //spacevalue ssddd
}
1

There are 1 best solutions below

0
On

"nodeValue returns multiple and all the values in child nodes"

Because that is what you asked for with . $rootNodeParent->nodeValue . there.

The string-value of the root node is the concatenation of the string-values of all text node descendants of the root node in document order.

"For every type of node, there is a way of determining a string-value for a node of that type. For some types of node, the string-value is part of the node; for other types of node, the string-value is computed from the string-value of descendant nodes."

Ref https://www.w3.org/TR/1999/REC-xpath-19991116/#data-model