简体   繁体   English

从XML到JSON的转换

[英]Transformation from XML to JSON

Is there a standard way to transform an input XML document with structure (scheme) of my choice to an output JSON object with structure (scheme) of my choice? 是否有一种标准方法将具有所选结构(方案)的输入XML文档转换为具有所选结构(方案)的输出JSON对象?

If it were transformation from input XML to output XML, I would use XSLT. 如果是从输入XML到输出XML的转换,我将使用XSLT。

I can image the following three approaches: 我可以想象以下三种方法:

  1. Direct transformation from XML to JSON, ie a way to describe transformation XML -> JSON just like XSLT describes transformation XML -> XML. 从XML到JSON的直接转换,即描述转换XML-> JSON的方法,就像XSLT描述转换XML-> XML一样。

  2. I am aware of JSONML. 我知道JSONML。 It is a lossless JSON representation of arbitrary XML document. 它是任意XML文档的无损JSON表示形式。 However, the resulting JSON object does not have the structure of my choice. 但是,结果JSON对象没有我选择的结构。 If there were some standard way to describe transformation JSON -> JSON, I would chain XML -> JSONML and JSONML -> JSON. 如果有一些描述转换JSON-> JSON的标准方法,我将链接XML-> JSONML和JSONML-> JSON。

  3. If there were the opposite to JSONML (let's call it "XMLSON", ie a lossless XML notation of arbitrary JSON object), I would chain XML -> XMLSON (via XSLT) and XMLSON -> JSON. 如果与JSONML相反(我们称其为“ XMLSON”,即任意JSON对象的无损XML表示法),我将链接XML-> XMLSON(通过XSLT)和XMLSON-> JSON。

All the three options have some "if there were". 所有这三个选项都有一些“如果存在”。 I wonder if there really is some technology to achieve the goal. 我想知道是否真的有某种技术可以实现这一目标。

Thanks. 谢谢。

The output of XSLT does not need to be XML, so if you are comfortable using that, you can go ahead and use it to output JSON. XSLT的输出不需要是XML,因此如果您愿意使用它,可以继续使用它来输出JSON。

A quick search showed up this, which might be a good example for you to start from: https://github.com/bramstein/xsltjson 快速搜索显示了这一点,这可能是您从以下位置开始的一个很好的示例: https : //github.com/bramstein/xsltjson

It defines an XSLT function which takes an XML tree as input, and generates a string as output. 它定义了一个XSLT函数,该函数将XML树作为输入,并生成一个字符串作为输出。 Looking into the source, the basic approach is to generate an XML tree with nodes for each JSON object, array, and value, and then apply templates to that which output the JSON syntax itself. 从源头来看,基本方法是为每个JSON对象,数组和值生成带有节点的XML树,然后将模板应用于输出JSON语法本身的模板。

For instance, to output a JSON array, it first generates an XML node of <json:array>...</json:array> , and then applies this template: 例如,要输出一个JSON数组,它首先生成一个<json:array>...</json:array>的XML节点,然后应用以下模板:

  <xsl:template match="json:array" mode="json">
    <xsl:variable name="values">
      <xsl:apply-templates mode="json"/>
    </xsl:variable>
    <xsl:text/>[<xsl:text/>
      <xsl:value-of select="string-join($values/value,',')"/>
    <xsl:text/>]<xsl:text/>
  </xsl:template>

XSLT 3支持将任何XML转换为https://www.w3.org/TR/xslt-30/#schema-for-json中定义的JSON的XML表示形式,然后允许您使用https:// www。 w3.org/TR/xslt-30/#func-xml-to-json将特定的XML转换为JSON。

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

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