如何用PHPDOM分别解析PCDATA和子元素?

How to parse PCDATA and child element separately with PHP DOM?

我正在尝试解析 XML 的 dtbook,其中包含级别(1、2 和 3),稍后又包含 p 标签。我正在使用 PHP DOM 进行此操作。 Link to XML

在这些 p-tags 的一部分中有 noteref-tags。我确实掌握了这些,但似乎我能得到的唯一结果是 noteref 出现在 p-tag 之前或之后。我需要一些 noterefs 出现在 p-tag 内;或者换句话说,它们实际应该在的位置。

<p>Special education for the ..... <noteref class="endnote" idref="fn_5"
id="note5">5</noteref>. Interest ..... 19th century <noteref class="endnote"
idref="fn_6" id="note6">6</noteref>.</p>

这是我现在为 p-tag 获得的代码。在此之前,我正在遍历 dt-book 以获取 p-tag。效果不错。

if($level1->tagName == "p") {
    echo "<p>".$level1->nodeValue;
    $noterefs = $level1->childNodes;
    foreach($noterefs as $noteref) {
        if($noteref->nodeType == XML_ELEMENT_NODE) {
            echo "<span><b>".$noteref->nodeValue."</b></span>";
        }
    }  
    echo "</p><br>";
}

这些是我得到的结果:

Special education for the ..... 5. Interest ..... 19th century 6.56

56Special education for the ..... 5. Interest ..... 19th century 6.

我还希望 p-tag 显示 noteref-tag 中的内容。这应该由 noteref-tag 完成(仅)。

那么,有人知道可以做些什么来解决这些问题吗?感觉就像我用谷歌搜索并尝试了几乎所有的东西。

DOMNode->nodeValue (which in PHP's DOMElement is the same as DOMNode->textContent) 将包含来自其自身及其所有降序节点的完整文本内容。或者,更简单一点:它包含节点的完整内容,但删除了所有标签。

您可能想尝试的是类似以下内容(未经测试):

if($level1->tagName == "p") {
    echo "<p>";
    // loop through all childNodes, not just noteref elements
    foreach($level1->childNodes as $childNode) {
      // you could also use if() statements here, of course
      switch($childNode->nodeType) {
        // if it's just text
        case XML_TEXT_NODE:
          echo $childNode->nodeValue;
        break;
        // if it's an element
        case XML_ELEMENT_NODE:
          echo "<span><b>".$childNode->nodeValue."</b></span>";
        break;
      }
    }  
    echo "</p><br>";
}

请注意,这仍然相当脆弱。例如:如果 <noteref> 元素之外的任何其他元素出现在 <p> 元素中,它们也将被包裹在 <span><b> 元素中。

希望我至少给了你一个线索,说明为什么你的结果 <p> 元素也显示了子元素的内容。


附带说明:如果您想要实现的是将 XML 文档的内容转换为 HTML 或其他一些 XML 结构,它可能会有所回报查看 XSLT。请注意,学习曲线可能很陡峭。