Javascript即时添加cdata部分?
我在使用xml节点属性中存在的特殊字符时遇到问题。 为了解决这个问题,我试图将属性渲染为子节点,并在必要时使用cdata部分来绕过特殊字符。 问题是,我似乎无法正确地将cdata部分附加到节点。
我正在迭代源xml节点的属性并创建新节点。 如果attribute.name =“description”我想将attribute.text()放在cdata部分并附加新节点。 这就是我跳过赛道的地方。
// newXMLData is the new xml document that I've created in memory for (var ctr =0;ctr< this.attributes.length;ctr++){ // iterate over the attributes if( this.attributes[ctr].name =="Description"){ // if the attribute name is "Description" add a CDATA section var thisNodeName = this.attributes[ctr].name; newXMLDataNode.append("" ); var cdata = newXMLData.createCDATASection('test'); // here's where it breaks. } else { // It's not "Description" so just append the new node. newXMLDataNode.append("" + $(this.attributes[ctr]).text() + "" ); } }
有任何想法吗? 还有另一种方法来添加cdata部分吗?
这是源代码的示例片段……
<row pSiteID="4" pSiteTile="Test Site Name " pSiteURL="http://www.cnn.com" ID="1" Description="blah blah blah since June 2007. T
blah blah blah blah " CreatedDate="2010-09-20 14:46:18" Comments="Comments example.
" >
这就是我要创造的……
4 Test Site Name http://www.cnn.com 1 <![CDATA[blah blah blah since June 2007. T
blah blah blah blah 2010-09-20 14:46:18
我遇到过同样的问题。 我试图将CDATA附加到xml节点,所以我认为它就像添加如此简单:
valueNode[0].text = ""; //valueNode[0] represents " "
这不起作用,因为整个事物将被解释为文本因此<(小于)和>(大于)将被自动替换。
你需要做的是通过执行以下操作使用createCDATASection:
var tmpCdata = $xmlDoc[0].createCDATASection(escape("muzi test 002")); //i'm also escaping special charactures as well valueNode[0].appendChild(tmpCdata);
结果将是:
Brettz9(在之前的回答中)解释了如何做到这一点,但非常复杂,因此我只想添加更简单的解决方案。
谢谢,
不确定浏览器对document.implementation.createDocument或createCDataSection的支持,但这至少在Mozilla中有效: