使用XSLT对XML中的类似节点进行分组

时间:2009-07-21 13:51:26

标签: xml xslt

我有以下XML结构

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <BookingGroup>
        <PostCodes>
            <PostCode >AB</PostCode>
            <PostCode >AL</PostCode>
        </PostCodes>
    </BookingGroup>
    <BookingGroup>
        <PostCodes>
            <PostCode >AB</PostCode>
            <PostCode >D</PostCode>
        </PostCodes>
    </BookingGroup>
</Root>

现在对于整个Xml中的每个邮政编码AB,我需要输出为:

<Root>
    <Child>
        <Child1>
        </Child1>
        <Child1>
        </Child1>
</root>

因为有两个AB邮政编码我需要两个child1元素。

1 个答案:

答案 0 :(得分:1)

如果您正在寻找那个文字输出,那么

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:variable name="firstNode" select="//PostCode[1]"/>
  <!-- for a literal value use <xsl:variable name="firstNode">AB</xsl:variable> -->

  <xsl:template match="Root">
    <Root>
      <Child>
    <xsl:apply-templates select="//PostCode"/>
      </Child>
    </Root>
  </xsl:template>

  <xsl:template match="PostCode">
    <xsl:if test=".=$firstNode">
      <Child1>
    <xsl:apply-templates select="@* | node()"/>
      </Child1>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

如果您正在寻找将输出输入中的任何节点的通用解决方案,请尝试使用

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:variable name="firstNode" select="//PostCode[1]"/>
  <!-- for a literal value use <xsl:variable name="firstNode">AB</xsl:variable> -->

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="PostCode">
    <xsl:if test=".=$firstNode">
      <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
相关问题