xml到json映射挑战 [英] xml to json mapping challenge

查看:125
本文介绍了xml到json映射挑战的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乍一看,我认为在javascript中使用xml数据就像查找xml-to-json库并将我的xml转换为javascript对象树一样简单。



<然而,现在,我意识到可以在xml中创建不直接映射到json的结构。



具体来说,这个:

 < parentNode> 
< fooNode> data1< / fooNode>
< barNode> data2< / barNode>
< fooNode> data3< / fooNode>
< / parentNode>

我发现的xml-to-json工具将之前的内容转换为如下内容:

  {
parentnode:{
foonode:[
'data1',
' data3'
],
barnode:'data2'
}

}



其中,子节点的顺序已更改。我需要保留我的子节点的顺序。任何人都有任何比



更优雅的解决方案a)放弃自动转换的想法,只是设计我自己的javascript对象结构并编写代码来处理这个特定的xml架构





b)放弃任何转换的想法,并将我的xml数据保留为xml文档然后我将遍历。

解决方案

已建立从XML到JSON的映射,但有局限性(参见 在XML和JSON之间转换 )以及从JSON到XML的映射(请参阅JSONx 此处定义并且 IBM的转换规则)。但是,从XML到JSON的保留顺序的映射尚未定义。要完全捕获XML的所有方面,应该在JSON中表达 XML Infoset 。如果您只关心XML元素(没有处理说明等),我会选择这种结构:

  [
parentNode,
{} / * attributes * /
[
[fooNode,{},[data1]]
[fooNode,{ },[data2]]
[fooNode,{},[data3]]
]
]

我实现了与XML和Perl数据结构之间的映射相同的映射,就像JSON一样, XML :: Struct 。该结构进一步对应于 MicroXML 的抽象数据模型,这是XML的简化子集。


At first glance, I thought using xml data in javascript would be as simple as finding an xml-to-json library and turning my xml into a javascript object tree.

Now, however, I'm realizing that it's possible to create structures in xml that don't map directly to json.

Specifically, this:

<parentNode>
    <fooNode>data1</fooNode>
    <barNode>data2</barNode>
    <fooNode>data3</fooNode>
</parentNode>

The xml-to-json tools I've found convert the previous to something like this:

{
parentnode:{
    foonode:[
        'data1',
        'data3'
    ],
    barnode:'data2'
}

}

in which, the order of the child nodes has been changed. I need to preserve the order of my child nodes. Anyone have any solution that's more elegant than

a) abandoning the idea of automatic conversion and just designing my own javascript object structure and writing code to handle this specific xml schema

or

b) abandoning the idea of any conversion at all, and leaving my xml data as an xml document which I'll then traverse.

解决方案

There are established mappings from XML to JSON with limitations (see Converting Between XML and JSON) and mappings from JSON to XML (see JSONx as defined here and conversion rules by IBM). A mapping from XML to JSON that preserves order, however, has not been defined yet. To fully capture all aspects of XML, one should express the XML Infoset in JSON. if you only care about XML elements (no processing instructions, etc.), I'd choose this structure:

[
  "parentNode",
  { } /* attributes */
  [ 
    [ "fooNode", { }, [ "data1" ] ]
    [ "fooNode", { }, [ "data2" ] ]
    [ "fooNode", { }, [ "data3" ] ]
  ]
]

I implemented the same mapping as mapping between XML and Perl data structures that are just like JSON with XML::Struct. The structure further corresponds to the abstract data model of MicroXML, a simplified subset of XML.

这篇关于xml到json映射挑战的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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