如何将XML转换为JSON?

时间:2011-06-01 15:44:43

标签: xml json porting

作为毕业的一部分,我必须将XML文件迁移到CouchDB。将文件的结构转换为JSON完全没问题,但有一部分我无法弄清楚如何实际转换:

<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功能。

这个问题的“最佳做法”或解决方案是什么?

2 个答案:

答案 0 :(得分:2)

以下方法可行,但PITA可以使用。代表每个标签如下:

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

content作为文本数组(标记之外)或标记。

忽略空格和缩进,您的代码段将变为:

{
  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,为此,数据结构是完全可预测和规则的非常有用。

答案 1 :(得分:0)

使用Unicode简化anonymous block boxes的转换:

JSON.stringify({"domelement": 
     {
     "p": "We beg to send us immediately [...]",
    "note": {"p":"In the original, [...]"}, 
    "add": "by post \u0022one copy of\u0022", 
    "title": "A Book \u0022by\u0022",
    "choice": [{"abbr":"Mrs."}, {"expan":"Misses \u0022Jane Smith\u0022 \u0022As soon\u0022 \u0022we know the\u0022"}],
    "choice": {"sic":"prize"},
    "corr": "price \u0022the amount [...]\u0022"
    }
 })

<强>参考