如何使用XSLT在XML中动态添加子元素,同时删除XML中的一些子元素



我是XSLT的新手,正在尝试以下操作。我已经攻击了XMLs

i.    Rename Rate_Recurring name to rateAttributeLookup
ii.   Removing Start_Date and Rate child elements from xml
iii.  Converting Bill_Code_New and Inter_Minute_Allowance into new child elements as below 

但我在执行ii操作时遇到了问题。我有嵌套的XML,所以你能为我提供通用的解决方案吗。感谢您的帮助

输入XML

<Package>
<Rate_Recurring Pattern="SimpleRRate" xsi:type="Voice_Recurring_Rate" ID="3ba5c15b-e347-4af1-875d-809e8443a4c3">
<Start_Date>2020-04-24</Start_Date>
<Rate>0</Rate>
<Bill_Code_New ID="e0a5ddae-3d6b-44ca-90fd-e38ea0c9324b" xsi:type="Lookup_Bill_Code" Pattern="Lookup" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>B9999</Name>
</Bill_Code_New>
<Inter_Minute_Allowance ID="dfedfdcb-4541-44c0-b0a3-575140fbde05" xsi:type="Lookup_Inter_Minute_Allowance" Pattern="Lookup" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>Unlimited</Name>
</Inter_Minute_Allowance>
<Bill_Code>B9999</Bill_Code>
</Rate_Recurring>
</Package>

输出XML

<Package>
<rateAttributeLookup>
<element>
<elementName>Bill_Code_New</elementName>
<rateAttributeId>e0a5ddae-3d6b-44ca-90fd-e38ea0c9324b</rateAttributeId>
</element>
<element>
<elementName>Inter_Minute_Allowance</elementName>
<rateAttributeId>dfedfdcb-4541-44c0-b0a3-575140fbde05</rateAttributeId>
</element>
</rateAttributeLookup>
</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>
<xsl:template match="*[@Pattern = 'SimpleNRRate'  or @Pattern = 'SimpleRRate'] ">
<rateAttributeLookup>
<xsl:apply-templates select="node()"/>
<xsl:for-each select="*">
<xsl:if test="@ID">
<elementName>
<xsl:value-of select="name()"/>
</elementName>
<rateAttributeId>
<xsl:value-of select="@ID"/>
</rateAttributeId>
</xsl:if>
</xsl:for-each> 
</rateAttributeLookup>
</xsl:template>
</xsl:stylesheet>

这样试试?

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="Rate_Recurring">
<rateAttributeLookup>
<xsl:apply-templates/>
</rateAttributeLookup>
</xsl:template>
<xsl:template match="Bill_Code_New | Inter_Minute_Allowance">
<element>
<elementName>
<xsl:value-of select="name()"/>
</elementName>
<rateAttributeId>
<xsl:value-of select="@ID"/>
</rateAttributeId>
</element>
</xsl:template>
<xsl:template match="Start_Date | Rate"/>
</xsl:stylesheet>

最新更新