简体   繁体   English

使用XSLT将XML中的相似节点分组

[英]Group Similar nodes in XML using XSLT

I have the following XML structure 我有以下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>

Now for every post code AB in the entire Xml I need the output as: 现在,对于整个Xml中的每个邮政编码AB,我都需要输出为:

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

because there are two AB postcode I need two child1 elements. 因为有两个AB邮政编码,所以我需要两个child1元素。

If you are looking for that literal output, this will do 如果您正在寻找该文字输出,则可以

<?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>

If you are looking for a general solution that will output whatever nodes are in the input try this 如果您正在寻找将输出输入中所有节点的通用解决方案,请尝试以下操作

<?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>

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

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