如何将XML转换为JSON? [英] How to translate XML to JSON?

查看:327
本文介绍了如何将XML转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为毕业的一部分,我必须将XML文件迁移到CouchDB.将文件的结构转换为JSON完全没有问题,但是有一部分我不知道如何进行实际转换:

As part of my graduation I have to migrate XML files to CouchDB. To convert the structure of the file to JSON is no problem at all, but there's one part which I can't figure out how to actually convert:

<p>We beg to send us immediately [...] <note>
  <p>In the original, [...]</p>
</note><lb/><add>by post</add> one copy of 
<title>A Book</title> by <persName>
  <choice><abbr>Mrs.</abbr><expan>Misses</expan></choice>Jane Smith</persName>.
As soon<lb/> we know the <choice>
                    <sic>prize</sic>
                    <corr>price</corr>
                </choice>the amount [...]<lb/> by post.<lb/>
</p>

我想坚持使用JSON,并且不要在JSON中使用XML,因为那样的话,我需要为程序实现XML功能.

I'd like to stick to JSON and don't use XML within JSON, as I would need to implement XML capabilities to my program then.

该问题的最佳做法"或解决方案是什么?

What would be 'best practices' or solutions to this problem?

推荐答案

尽管可以使用PITA,但以下方法可以工作.代表每个标签s如下:

The following will work, though is a PITA to work with. Represent each tag s follows:

{
  attr => {...},
  tag => "...",
  content => [...]
}

content作为文本数组(在标签外部)或其他标签.

And content as an array of text (outside of tags) or else tags.

忽略空白和缩进,您的代码片段将变成:

Ignoring whitespace and indentation your snippet would become something like:

{
  tag => "p",
  content => [
    "We beg to send us immediately [...]",
    {
      tag => "note",
      content => [
        {
          tag => "p",
          content => [ "In the original, [...]" ]
        }
      ]
    },
    { tag => "lb" },
    {
      tag => "add",
      content => [ "by post" ],
    },
    " one copy of ",
    {
      tag=> "title",
      content => [ "A Book" ],
    },
    " by ",
    {
      tag => "persName",
      content => [
        {
          tag => "choice",
          content => [ ... ]
        }
      ],
    },
    ...
  ]
}

(抱歉,我很无聊.)

请注意,数据结构非常重复且冗长.但是您将以编程方式处理JSON,因此对于数据结构而言,可预测性和规则性非常好.

Note that the data structure is very repetitive and verbose. But you'll be processing the JSON programmatically, and for that it is very useful that the data structure is perfectly predictable and regular.

这篇关于如何将XML转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆