簡體   English   中英

< 和 > 使用 DOM 文檔創建 XML 時的節點值問題

[英]< and > in node value problem in creating XML using DOM Document

我正在創建一個腳本來使用 DOM 文檔將 json 解析為 XML。 當我想將 < 和 > 放在 createElement 部分的節點值中時遇到了問題。 <>被轉換成&lt; &gt; 我希望它保持原樣。

我怎樣才能讓它保持原樣?

這是我當前的代碼:

    $dom->encoding = 'utf-8';
    $dom->xmlVersion = '1.0';
    $dom->formatOutput = true;

    $root = $dom->createElement('questions', "<![CDATA[what animal walk above the wave?]]>");

    ....

    $dom->save('file.xml');

我的 XML 結果:

<question>&lt;![CDATA[what animal walk above the wave?]]&gt;</question>

我期待着:

<question><![CDATA[what animal walk above the wave?]]></question>

XML 的樹模型和序列化表示是完全不同的東西。 在樹模型中,您使用字符串值創建節點; 當樹被序列化為詞法 XML 時,就會生成標記。 因此,您不能將詞法 XML 放入 DOM 並期望它在序列化后繼續存在。

DOMDocument::createElement() (和SimpleXMLElement::addChild() )的第二個參數以及DOMElement::$nodeValue具有相同的奇怪行為。 它們轉義<> ,但不是& 為了避免 DOM 中的問題,您可以使用DOMDocument::createTextNode()DOMNode::$textContent CDATA 節是一種節點,您需要為它們使用DOMDocument::createCDATASection()

$document = new DOMDocument();
$examples = $document->appendChild($document->createElement('examples'));
$examples
  ->appendChild($document->createElement('one'))
  // append an explcit text node - original DOM approach
  ->appendChild($document->createTextNode('foo > bar'));
$examples
  ->appendChild($document->createElement('two'))
  // write textContent - DOM Level 3 shortcut
  ->textContent = 'foo > bar';
$examples
  ->appendChild($document->createElement('three'))
  // add CDATA sectiom
  ->appendChild($document->createCDATASection('foo > bar'));

$document->formatOutput = TRUE;
echo $document->saveXML();

輸出:

<?xml version="1.0"?>
<examples>
  <one>foo &gt; bar</one>
  <two>foo &gt; bar</two>
  <three><![CDATA[foo > bar]]></three>
</examples>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM