换行符在 DOMDocument 中产生文本节点 - 我应该如何处理这个

Line breaks produce Text nodes in DOMDocument - how should I handle this

我正在使用 php 的 DOMDocument library and read an XML string with loadXML。然后,我使用以下代码遍历标记为 "Info" 的节点的子节点:

$doc = new \DOMDocument();
$doc->loadXML(
'<?xml version="1.0" encoding="UTF-8"?>
<GAEB xmlns="http://www.gaeb.de/GAEB_DA_XML/DA31/3.2">
 <Info>
  <Version>3.2</Version>
  <VersDate>2013-10</VersDate>
  <Date>2014-10-10</Date>
  <Time>12:28:28</Time>
  <ProgSystem>GAEB Zertifizierung</ProgSystem>
  <ProgName>BVBS</ProgName>
 </Info>
</GAEB>'
);

$Info = $doc->getElementsByTagName("Info");

foreach ($Info as $element) {
    echo "[". $element->nodeName. "]";
    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
        echo "[" . $node->nodeName . "]";
        echo  $node->nodeValue;
    }
}

此节点有 6 个子节点,但是迭代有 13 次运行。那是因为有解释为 Text nodes 的空白字符。如果我查看每个节点 $node->nodeType,它会显示 6 个真实子节点的 1 和 7 个子节点的 3,内容为 \n。现在的问题是,我该如何应对? DOMDocument 包含那些文本节点是否可以,我应该 "continue" 用 if($node->nodeType===3) continue 之类的东西覆盖它们,或者我会尝试在加载 xml 时更早地删除那些空格。仅从输入 xml 中删除 \n 是行不通的,因为节点之间的空格(例如 > <)将被解释为文本节点。

示例文件

<?xml version="1.0" encoding="UTF-8"?>
<GAEB xmlns="http://www.gaeb.de/GAEB_DA_XML/DA31/3.2">
 <Info>
  <Version>3.2</Version>
  <VersDate>2013-10</VersDate>
  <Date>2014-10-10</Date>
  <Time>12:28:28</Time>
  <ProgSystem>GAEB Zertifizierung</ProgSystem>
  <ProgName>BVBS</ProgName>
 </Info>
</GAEB>

可以使用LIBXML_NOBLANKS选项忽略空白节点,如下所示:

$doc->loadXML($xml, LIBXML_NOBLANKS);