jrock2004
jrock2004

Reputation: 3501

Invalid character entity parsing xml

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

Upvotes: 9

Views: 14617

Answers (2)

Jordan.J.D
Jordan.J.D

Reputation: 8113

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);
        }
    });

Upvotes: 8

jrock2004
jrock2004

Reputation: 3501

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,"&amp;")
                    .replace(/-/g,"&#45;");

Thanks

Upvotes: 14

Related Questions