0

我尝试解析 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 + "&nbsp;&nbsp;&nbsp;");
            }
        }
    }
};

我的 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 代码是正确且格式正确的。

4

2 回答 2

0
app.xmlDoc = parser.parseFromString(result.txt,"text/xml"); 

实际上应该是:

app.xmlDoc = parser.parseFromString(result.text,"text/xml"); 

result.text 中缺少“e”

于 2014-04-16T10:33:14.117 回答
0

在再次阅读 Valencia 的评论和“错误”的输出并思考之后,我发现出了什么问题。所以“错误”输出只是 HTML 格式的错误消息,我打印每个标签。消息本身说:

This page contains the following errors:
error on line 1 at column 14: String not started expectin ' or "

开头应该是这样的

<?xml version="1.0" encoding="UTF-8"?>

但是在创建 QR 码时添加了反斜杠

<?xml version=\"1.0\" encoding=\"UTF-8\"?>

第一个反斜杠位于第 14 列。

当我创建一个静态 XML 字符串时,我插入反斜杠来掩盖“””,所以我的声明和 QR 码中的 XML 代码看起来相等。但它们不是,因为静态 XML 字符串不包含反斜杠。并且这些反斜杠在解析时会导致错误。

最简单的解决方案是不将 XML 信息放入 QR 码中。所以直接从第一个节点开始。

谢谢你的帮助。

于 2014-04-23T07:42:30.567 回答