【问题标题】:Group Similar nodes in XML using XSLT使用 XSLT 对 XML 中的相似节点进行分组
【发布时间】:2009-07-21 13:51:26
【问题描述】:

我有以下 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 元素。

【问题讨论】:

  • 这个问题,按照目前的措辞,是难以理解的。
  • 我想知道人们是否曾经阅读他们写的东西?没有人可以实际上如此残缺地同时使用 XML。但话又说回来,也许这是可能的。 xkcd.com/481

标签: xml xslt


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多