Home > Net >  Every single XML parser I tried doesn't work with this specific XML
Every single XML parser I tried doesn't work with this specific XML

Time:09-02

index.js

const fs = require("node:fs")
const xml2js = require('xml2js')

const parser = new xml2js.Parser()

const data = fs.readFileSync('test.xml', "utf8")
const json = JSON.parse(await parser.parseStringPromise(data))

console.log(JSON.stringify(json))

test.xml

<thing>
    <2 value="300.0"/>
    <3 value="1.0"/>
</thing>

All of this only returns this error:

Error: Unencoded <
Line: 1
Column: 3
Char: 2

I've been stuck trying to figure out what is wrong for hours straight, I tried 3 xml2json, xml2js and xml-js. None of them worked and they return the same error.

CodePudding user response:

Your XML is invalid. An XML element name cannot start with a number.

https://www.w3.org/TR/REC-xml/#sec-common-syn

The first character of a Name must be a NameStartChar, and any other characters must be NameChars; this mechanism is used to prevent names from beginning with European (ASCII) digits or with basic combining characters. Almost all characters are permitted in names, except those which either are or reasonably could be used as delimiters. The intention is to be inclusive rather than exclusive, so that writing systems not yet encoded in Unicode can be used in XML names. See J Suggestions for XML Names for suggestions on the creation of names.

  • Related