DOM XML child nodes


DOM XML child nodes

如果我有一个XML,例如:

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

我想获得父节点的所有子节点(使用php为例),当我调用

$xmlDoc->loadXML('..');
$rootNode = $xmlDoc->documentElement;
$children = $rootNode->childNodes;

$children包含什么?是只包含<child>节点还是同时包含<child><grandchild>节点?

parent文档元素节点有3个子节点。元素节点child和两个包含节点前后空白的文本节点:

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

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

如果你在文档上禁用保留空白选项,它将在加载xml时删除空白节点。

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

string(10) "DOMElement"

要更灵活地获取节点,请使用Xpath。它允许你使用表达式来获取节点:

$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);
}
输出:

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