0

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
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
user9718914
  • 103
  • 9
  • If I like to obtain only a text value inside the root..( I know that it does not have any text).. what should be the code for this..I was expecting nodeValue to be empty or null. – user9718914 May 02 '18 at 19:29

1 Answers1

0

"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

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100