[英]< and > in node value problem in creating XML using DOM Document
我正在創建一個腳本來使用 DOM 文檔將 json 解析為 XML。 當我想將 < 和 > 放在 createElement 部分的節點值中時遇到了問題。 <
和>
被轉換成<
和>
我希望它保持原樣。
我怎樣才能讓它保持原樣?
這是我當前的代碼:
$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><![CDATA[what animal walk above the wave?]]></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 > bar</one>
<two>foo > bar</two>
<three><![CDATA[foo > bar]]></three>
</examples>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.