Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid character entity parsing xml

Tags:

node.js

xml2js

I am trying to parse a string of xml and I getting an error

[Error: Invalid character entity
Line: 0
Column: 837
Char:  ]

Does xml not like brackets? Do I need to replace all the brackets with something like \\]. Thanks

like image 541
jrock2004 Avatar asked Jul 22 '14 00:07

jrock2004


2 Answers

Ok, the invalid character was the dash and an &. I fixed it by doing the following:

xml = data.testSteps.replace(/[\n\r]/g, '\\n')
                    .replace(/&/g,"&")
                    .replace(/-/g,"-");

Thanks

like image 109
jrock2004 Avatar answered Oct 21 '22 09:10

jrock2004


Using a node domparser will get around having to do a string replace on every character that is not easily parsed as a string. This is especially useful if you have a large amount of XML to parse that may have different characters.

I would recommend xmldom as I have used it successfully with xml2js

The combined usage looks like the following:

var parseString = require('xml2js').parseString;
var DOMParser = require('xmldom').DOMParser;

var xmlString = "<test>some stuff </test>";
var xmlStringSerialized = new DOMParser().parseFromString(xmlString, "text/xml");
    parseString(xmlStringSerialized, function (err, result) {
        if (err) {
            //did not work
        } else {
            //worked! use JSON.stringify() 
            var allDone = JSON.stringify(result);
        }
    });
like image 40
Jordan.J.D Avatar answered Oct 21 '22 09:10

Jordan.J.D