簡體   English   中英

XSLT 將 1 xml 中標簽的文本值替換為另一個 xml 檢查屬性是否相同后替換文本值

[英]XSLT Replacing text value of the tag in 1 xml with another xml after checking if attribute are the same then replace text value

我是這方面的初學者,我想使用 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>

在檢查類別中的屬性ID之后與file2.Z0F635D0E0F3874FF38B581C132E6C7A7Z中的類別中的屬性ID與ID相同,然后從File1.z0f635D0EF38774FF58B581C132E6C72E7AP7替換元素文本類別中

文件2.xml

<ITEM>
      <CATEGORY2 id="12308">CDFreplacetext<CATEGORY2>
      <CATEGORY2 id="12306">ABCreplacetext<CATEGORY2>
</ITEM>

這是我想要的 output

Output:

<shop>
    <SHOPITEM>
        <CATEGORY id="12306">ABCreplacetext</CATEGORY> 
    </SHOPITEM>
    <SHOPITEM>
        <CATEGORY id="1233">SDFclothes</CATEGORY>
    </SHOPITEM>
    <SHOPITEM>
        <CATEGORY id="12308">CDFreplacetext</CATEGORY>
    </SHOPITEM>
</shop>

如果您可以使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM