如何使用 XSLT 同时为 XML 添加属性和子元素

How to add Attribute as well as child element at same time for XML using XSLT

我是 XSLT 的新手,我正在尝试在 XML 上执行以下操作(添加 ID 作为子元素以及模式作为包的属性)。 我已经提供了预期的输出以及我的 XSLT。 你能不能给我提供通用的解决方案,因为为了简单起见,我在 xml 中嵌套了包节点 我提供了简单的 XML.As 现在我只能在我的 xml 上添加属性更改(模式)我的 ID 相关更改(子元素)正在被覆盖。

输入XML

<Package ID="b9e05dea-80dc-436b-bea6-497161b08342" xsi:type="Mobile_Plan_Package_Template" BusinessID="000126" Path="/Package/Product/Launch_Entity" Version="1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>SuperCare Plan</Name>
</Package>

XSLT 的预期输出

<Package ID="b9e05dea-80dc-436b-bea6-497161b08342" pattern="Package" xsi:type="Mobile_Plan_Package_Template" BusinessID="000126" Path="/Package/Product/Launch_Entity" Version="1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>SuperCare Plan</Name>
<ID>b9e05dea-80dc-436b-bea6-497161b08342</ID>
</Package>

XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  exclude-result-prefixes="xsi">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
    
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <!--To Add IDs in all nodes-->
    <xsl:template match="*[@ID]" >      
            <xsl:copy>  
            <xsl:apply-templates select="@*|node()"/>
            <ID>
                <xsl:value-of select="current()/@ID" />
            </ID>
            
           </xsl:copy>
                    
    </xsl:template>
    <!--To Add IDs in all nodes-->

    
<!--To Add Attributes in package node-->
   <xsl:template match="*[local-name() = 'Package']">

        <xsl:copy>
            <xsl:attribute name="pattern">
                <xsl:value-of select="local-name()"/>
            </xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>

    </xsl:template>
<!--To Add Attributes in package node-->


</xsl:stylesheet>

提前感谢您的帮助

AFAICT,这应该适合你:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="Package">
    <xsl:copy>
        <xsl:attribute name="pattern">
            <xsl:value-of select="local-name()"/>
        </xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
        <ID>
            <xsl:value-of select="@ID"/>
        </ID>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>