如何将XML元素组转换为JSON列表?

[英]How to convert groups of XML elements to JSON lists?


Is it possible to apply a template that only matchings on the unique attributes?

是否有可能应用一个只匹配唯一属性的模板?

<node name="region">1</node>
<node name="region">2</node>
<node name="region">3</node>
<node name="place">a</node>
<node name="place">b</node>
<node name="title">test</node>

I want to execute a template once for @name="region" and once for @name="place". Can this be done using XSLT/XPath 1.0?

我想为@name="region"执行一个模板,为@name="place"执行一个模板。可以使用XSLT/XPath 1.0实现这一点吗?

My ultimate goal is JSON output that looks like this:

我的最终目标是JSON输出如下:

"container":{
"region":["1","2","3"],
"place":["a","b"],
"title":"test"
}

1 个解决方案

#1


5  

Muenchian Grouping Method

You can use the Muenchian Method to solve your grouping problem.

您可以使用Muenchian方法来解决分组问题。

This input XML,

这个输入XML,

<container>
  <node name="region">1</node>
  <node name="region">2</node>
  <node name="region">3</node>
  <node name="place">a</node>
  <node name="place">b</node>
  <node name="title">test</node>
</container>

provided to this XSLT,

这个XSLT提供,

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:key name="nodes-by-name" match="node" use="@name"/>

  <xsl:template match="container">
    <xsl:text>"container": {&#xa;</xsl:text>
      <xsl:for-each select="node[count(. | key('nodes-by-name', @name)[1]) = 1]">
      <xsl:value-of select="concat('&quot;', @name, '&quot;:')"/>
      <xsl:choose>
        <xsl:when test="count(key('nodes-by-name', @name)) = 1">
          <xsl:value-of select="concat('&quot;', ., '&quot;')"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:text>[</xsl:text>
          <xsl:for-each select="key('nodes-by-name', @name)">
            <xsl:value-of select="concat('&quot;', ., '&quot;')"/>
            <xsl:if test="position() != last()">,</xsl:if>
          </xsl:for-each>
          <xsl:text>]</xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:if test="position() != last()">,</xsl:if>
      <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
    <xsl:text>}</xsl:text>
  </xsl:template>

</xsl:stylesheet>

yields this XML output,

收益率这个XML输出,

"container": {
"region":["1","2","3"],
"place":["a","b"],
"title":"test"
}

as requested.

按照要求。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/10/12/adfd897b15155b2d8d60ea94a49621d4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com