XSLT - 对节点进行分组时缺少属性

XSLT - Missing attributes when grouping the nodes

这是 XML 输入、想要的输出、我的代码和我得到的错误结果的最小但完整的示例。

这是我的输入XML

<?xml version="1.0"?>
<R>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">1</p>
    </B>
  </M>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">2</p>
    </B>
  </M>
  <M>
    <H>1</H>
     <B>
        <p Ccy="GBP">3</p>
    </B>
  </M>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">4</p>
    </B>
  </M>
</R>

这是我当前的 XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

    <xsl:output indent="yes" />

     <xsl:template match="/*">
        <R>
            <M>
                <xsl:apply-templates select="M[1]/H | M/B" />
            </M>
        </R>
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

这是我当前的输出

如果您查看输出,会发现输出中缺少 Ccy="GBP"。请查看预期输出。

<?xml version="1.0" encoding="UTF-8"?>
<R xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <M>
      <H>1</H>
      <B>
        <p>1</p>
      </B>
      <B>
        <p>2</p>
      </B>
      <B>
        <p>3</p>
      </B>
      <B>
        <p>4</p>
      </B>
   </M>
</R>

预期输出

<?xml version="1.0" encoding="UTF-8"?>
<R xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <M>
      <H>1</H>
      <B>
        <p Ccy="GBP">1</p>
      </B>
      <B>
        <p Ccy="GBP">2</p>
      </B>
      <B>
        <p Ccy="GBP">3</p>
      </B>
      <B>
        <p Ccy="GBP">4</p>
      </B>
   </M>
</R>

Fiddle: https://xsltfiddle.liberty-development.net/ej9EGbG/31

     <xsl:template match="/*">
        <R>
            <M>
                <xsl:apply-templates select="M[1]/H | M/B" />
            </M>
        </R>
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:if test="@Ccy">
                <xsl:attribute name="Ccy">
                    <xsl:value-of select="@Ccy"/>
                </xsl:attribute>
            </xsl:if>

            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
Simply add attribute @Ccy.

如果您想复制所有属性,只需扩展应用模板来处理它们并设置一个复制它们的模板:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

    <xsl:output indent="yes" />

     <xsl:template match="/*">
        <R>
            <M>
                <xsl:apply-templates select="M[1]/H | M/B" />
            </M>
        </R>
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="@*">
        <xsl:copy/>
    </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ej9EGbG/34