简体   繁体   English

使用xml2js将XML解析为JSON时转换实体?

[英]Convert entities when parsing XML to JSON using xml2js?

I'm using a class to convert xml to json for my project like so:我正在为我的项目使用 class 将 xml 转换为 json,如下所示:

export class AccessionClass {
  constructor(accessionFilename) {
    this.accessionFilename = accessionFilename
    this.accessionXML = fs.readFileSync(this.accessionFilename).toString()
    const parser = new xml2js.Parser({ explicitArray: false })
    parser.parseString(this.accessionXML, (err, results) => {
      this.accessionJSON = results.accessions
    })...
  getJSONItem(itemNumber, callback) {
    let oneItem
    let items = this.accessionJSON.item.filter(item => {
      return item.accession === itemNumber
    })
    if (items.length > 1) {
      console.log('getJSONItem: ' + items.length + ' items for accession: ' + itemNumber)
    }
    callback(items[0])
  }

After calling getJSONItem the JSON string values have unconverted entities调用 getJSONItem 后,JSON 字符串值具有未转换的实体

(' & ...)

Am I missing an obvious option to do this?我错过了一个明显的选择吗? What is the best way to get these converted?转换这些的最佳方法是什么?

On closer inspection of the above you may observe that the entities were munged by something in my xml. Fixing that solved my problem.仔细检查以上内容,您可能会发现实体被我的 xml 中的某些东西弄脏了。修复它解决了我的问题。 I'll just have to hand edit them to fix them.我只需要手动编辑它们来修复它们。 Sorry for the false alarm.抱歉误报。

I know there's no other way you're going to do this with your hand to organize it.我知道没有其他方法可以用手来组织它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM