我尝试解析 XML 字符串并遇到一些问题。这是我目前的状态。我有一个读取 QR 码的 Cordova 应用程序(使用 BarcodeScanner 插件)。QR 码保存 XML 信息。当我阅读代码时,我想打印出 XML 代码。这是我尝试过的(重要部分):
var app = {
output: null,
xmlDoc: null,
// this function is called when I click a button
scanCode: function(){
//first parameter is a callback, which is called when a barcode is detected
cordova.plugins.barcodeScanner.scan(
function (result) {
alert(result.text);
var parser = new DOMParser();
**app.xmlDoc = parser.parseFromString(result.text,"text/xml");**
app.output = document.getElementById("codeInfo");
app.traverse(app.xmlDoc.documentElement, "");
},
function (error) {
alert("Scanning failed: " + error);
}
);
},
traverse: function(node, offset){
if(node.nodeType == 3){
app.output.innerHTML += "<b>" + offset + node.nodeValue + "</b><br>";
}else{
app.output.innerHTML += offset + node.nodeName + "<br>";
var childs = node.childNodes;
for(var i=0; i<childs.length; i++){
app.traverse(childs[i], offset + " ");
}
}
}
};
我的 XML 代码看起来像这样
<node><child1>text1</child1><child2>text2</child2></node>
所以我希望输出如下:
node
child1
text1
child2
text2
但我总是得到类似的东西:
html
body
parsererror
h3
This page contains the following errors:
...
当我使用静态文本时
var xml = "<node><child1>text1</child1><child2>text2</child2></node>"
并在标记行中使用它而不是“result.text”,一切都按预期工作。
所以也许'result.text'只是一个参考而不是价值?这可能是问题吗?我不是专家,所以我该如何解决这个问题?
PS:我从 QR-Code 获得的 XML 代码是正确且格式正确的。