9

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

4444
  • 3,541
  • 10
  • 32
  • 43
jrock2004
  • 3,229
  • 5
  • 40
  • 73
  • 2
    the report starts with [ and ends with ], the bad character is before the closing bracket. Reduce your XML file until it's a few lines that still has this problem, and add that to your question. We have no idea what you're working with right now. – Mike 'Pomax' Kamermans Jul 22 '14 at 00:41
  • Basically this is part os a json object. I know it has to be some character because if I pass in a different xml it works. So its something in the xml. I wish I could post the xml but its sensitive data – jrock2004 Jul 22 '14 at 00:43
  • Most of the xml that has brackets looks something like, "order set limit -Navigate to any product A [TBD]" without the quotes – jrock2004 Jul 22 '14 at 00:45

2 Answers2

12

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

jrock2004
  • 3,229
  • 5
  • 40
  • 73
8

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);
        }
    });
Gerben Rampaart
  • 9,853
  • 3
  • 26
  • 32
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
  • 1
    Seems really counter performant to invoque DOMParser just so that xml2js will not choke on nasty characters. Would anyone know a more bullet proof xml -> js object alternative? Thanks anyway, you saved my day. – MetaZebre Jan 17 '23 at 12:58