【问题标题】:XSL Transformation to split a single node into two nodes in the same levelXSL 转换将单个节点拆分为同一级别的两个节点
【发布时间】:2012-06-30 22:14:33
【问题描述】:

我有一个源 XML

<Cars>
  <Car>
    <Make>Fiat</Make>
    <Colors>
      <Color>RED</Color>
      <Color>BLUE</Color>
    </Colors>
  </Car>
  <Car>
    <Make>Volvo</Make>
    <Colors>
      <Color>RED</Color>
      <Color>WHITE</Color>
    </Colors>
  </Car>
  <Car>
    <Make>Renault</Make>
    <Colors>
      <Color>BLUE</Color>
      <Color>BLACK</Color>
    </Colors>
  </Car>
</Cars>

我想把它变成类似的东西

<Cars>
  <Detail>
    <Name>MakeName</Name>
    <Entry>Fiat</Entry>
    <Entry>Volvo</Entry>
    <Entry>Renault</Entry>
  </Detail>
  <Detail>
    <Name>AvailableColors</Name>
    <Entry>RED</Entry>
    <Entry>BLUE</Entry>
    <Entry>WHITE</Entry>
    <Entry>BLACK</Entry>
  </Detail>
<Cars>

我是 XSL 的新手,并且创建了一个来完成一半的处理,但我坚持将颜色作为目标中的单独元素获取

<xsl:template match="/">
  <Cars>
    <xsl:apply-templates />
  </Cars>
</xsl:template>

<xsl:template match="Cars">
  <xsl:apply-templates select="Car" />
</xsl:template>

<xsl:template match="Car">
  <Detail>
    <Name>MakeName</Name>
    <xsl:apply-templates select="Make" />
  </Detail>
</xsl:template>

<xsl:template match="Make">
  <Entry><xsl:value-of select"text()"/></Entry>
</xsl:template>

我无法为 &lt;Name&gt;AvailableColors&lt;/Name&gt; 创建 XSL,我对 XSL 很陌生,非常感谢任何帮助

【问题讨论】:

  • 旁注:应用转换后您的业务逻辑是否仍然有效?我希望您的结果中可以使用 WHITE Renault,但您的来源中没有。
  • 我们需要一个可以将汽车品牌和颜色作为单独的独特元素的 xml。业务逻辑是将源 xml 元素“Car”拆分为两个结果 xml 元素“Make”和“Color”

标签: xslt


【解决方案1】:

请参阅此答案中给出的通用“粉碎”解决方案

https://stackoverflow.com/a/8597577/36305

【讨论】:

  • 你好 :) OP 似乎是 XSLT 的新手,我想他会发现很难参考其他示例并设计自己的代码。
  • @infantprogrammer'Aravind':我现在也看到 OP 在切碎的意义上没有使用“分裂”一词。这只是常规分组。我将删除我的答案。
【解决方案2】:

这是一个 XSLT 1.0 样式表,展示了如何使用 Muenchian grouping 消除重复颜色:

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

<xsl:output indent="yes"/>

<xsl:key name="k1" match="Car/Colors/Color" use="."/>

<xsl:template match="Cars">
  <xsl:copy>
    <Detail>
      <Name>MakeName</Name>
      <xsl:apply-templates select="Car/Make"/>
    </Detail>
    <Detail>
      <Name>AvailableColors</Name>
      <xsl:apply-templates select="Car/Colors/Color[generate-id() = generate-id(key('k1', .)[1])]"/>
    </Detail>
  </xsl:copy>
</xsl:template>

<xsl:template match="Car/Make | Colors/Color">
  <Entry>
    <xsl:value-of select="."/>
  </Entry>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多