我正在尝试使用xml2js构建XML节点。当我添加用cdata包装的html标签时,它会创建一个单独的节点,如下所示。如果我将CDATA包装在“<>”中里面的值是未定义的。基本上我正在尝试创建XML文档,我可以从中获取节点值并使用jQuery / Angular在HTML文档中显示它。那些节点必须能够包含HTML标签
var xml2js = require('xml2js');
var parser = new xml2js.Parser({
explicitArray: false
});
var builder = new xml2js.Builder({
cdata: true
});
var test = "<parent>![CDATA[Hey There! <span> Buddy.</span>]]</parent>"
parser.parseString(test, function(err, result) {
var xml = builder.buildObject(result)
console.log(xml)
});
//Output
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
![CDATA[Hey There! ]]
<span> Buddy.</span>
</parent>
*/
var test2 = "<parent><![CDATA['Hey There! <span> Buddy.</span>']]></parent>";
parser.parseString(test, function(err, result) {
var xml = builder.buildObject(result)
console.log(xml)
});
//Output :
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent><![CDATA[undefined]]></parent>
*/
答案 0 :(得分:1)
您的首次测试 几乎 正确无误。你真的需要&lt; &GT; CDATA内容周围的符号。
此代码:
var xml2js = require('xml2js');
var parser = new xml2js.Parser({
explicitArray: false
});
var builder = new xml2js.Builder({
cdata: true
});
var test = "<parent><![CDATA[Hey There! <span> Buddy.</span>]]></parent>";
parser.parseString(test, function(err, result) {
var xml = builder.buildObject(result);
console.log(xml);
});
生成此输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent><![CDATA[Hey There! <span> Buddy.</span>]]></parent>
答案 1 :(得分:0)
它可以在没有解析器的情况下进行。 _有助于处理标签内的内部文本。
const xml2js = require('xml2js');
const builder = new xml2js.Builder({
cdata: true
});
const test = "Hey There! <span> Buddy.</span>";
const xml = builder.buildObject({
parent: {
_: test,
}
});
console.log(xml);