我是初學者,我想使用 xslt 來轉換我的 xml 檔案,但我缺乏知識和經驗來做到這一點。這是我想用 xsl 轉換的 file1.xml 的示例
檔案1.xml
<shop>
<SHOPITEM>
<CATEGORY id="12306">ABCclothes</CATEGORY>
</SHOPITEM>
<SHOPITEM>
<CATEGORY id="1233">SDFclothes</CATEGORY>
</SHOPITEM>
<SHOPITEM>
<CATEGORY id="12308">CDFclothes</CATEGORY>
</SHOPITEM>
</shop>
檢查 CATEGORY 中的屬性 id 是否與 file2.xml 中 CATEGORY2 中的 id 相同,然后將 file1.xml 中的元素文本 CATEGORY 替換為 file2.xml 中 CATEGORY2 中的元素文本
檔案2.xml
<ITEM>
<CATEGORY2 id="12308">CDFreplacetext<CATEGORY2>
<CATEGORY2 id="12306">ABCreplacetext<CATEGORY2>
</ITEM>
這是我試圖獲得的輸出
輸出:
<shop>
<SHOPITEM>
<CATEGORY id="12306">ABCreplacetext</CATEGORY>
</SHOPITEM>
<SHOPITEM>
<CATEGORY id="1233">SDFclothes</CATEGORY>
</SHOPITEM>
<SHOPITEM>
<CATEGORY id="12308">CDFreplacetext</CATEGORY>
</SHOPITEM>
</shop>
uj5u.com熱心網友回復:
如果您可以使用 XSLT 3.0 版(或 2.0;只需替換xsl:mode為身份轉換),我將使用xsl:key...
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="file2" select="document('file2.xml')"/>
<xsl:key name="cat2" match="CATEGORY2" use="@id"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="CATEGORY">
<xsl:copy>
<xsl:apply-templates select="@*,(key('cat2',@id,$file2)/node(),node())[1]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
如果您堅持使用 XSLT 1.0,請嘗試使用xsl:choose...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="file2" select="document('file2.xml')"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="CATEGORY">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:choose>
<xsl:when test="$file2//CATEGORY2[@id=current()/@id]">
<xsl:apply-templates select="$file2//CATEGORY2[@id=current()/@id]/node()"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="node()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/389427.html
