2013-05-04 160 views
0

在下面的XSLT我檢查以下XSLT替換空元素和屬性值

  1. 如果元素爲null,則替換然後與其他元素的值替換它。
  2. 如果該元素的屬性爲null,則將其替換爲常量值。

1正在工作,但2不是。

對於2我已經嘗試了兩件事情:

首先,使用xsl:if條件沒有工作。 它添加了一個具有相同節點名稱的新節點,而不是將值插入屬性。

第二我試圖使用該模板。那也行不通。 它完全消除了該節點並將該屬性添加到具有該值的父級。

此外,是否有可能以不同的方式或更好的方式做到這一點。

XSLT

<xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id"> 
    <xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id = ''"> 
     <xsl:copy> 
     <xsl:value-of select="//ns0:Broker/ns0:Party/ns0:Id"/> 
     </xsl:copy> 
    </xsl:if> 
    <!--<xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']"> 
     <xsl:copy> 
     <xsl:attribute name="Agency">Legacy</xsl:attribute> 
     <xsl:value-of select="'Legacy'"/> 
     </xsl:copy> 
    </xsl:if>--> 
    </xsl:template> 

    <xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']"> 
    <xsl:attribute name="Agency">Legacy</xsl:attribute> 
    </xsl:template> 

輸入

<ns0:Testing> 
    <ns0:Cedent> 
    <ns0:Party> 
     <ns0:Id Agency=""></ns0:Id> 
     <ns0:Name>Canada</ns0:Name> 
    </ns0:Party> 
    </ns0:Cedent> 
    <ns0:Broker> 
    <ns0:Party> 
     <ns0:Id Agency="Legacy">292320710</ns0:Id> 
     <ns0:Name>Spain</ns0:Name> 
    </ns0:Party> 
    </ns0:Broker> 
</ns0:Testing> 

輸出

<ns0:Testing> 
    <ns0:Cedent> 
     <ns0:Party> 
     <ns0:Id Agency="Legacy">292320710</ns0:Id> 
     <ns0:Name>Canada</ns0:Name> 
     </ns0:Party> 
    </ns0:Cedent> 
</ns0:Testing> 

回答

1
<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:ns0="some_namespace_uri" 
> 
    <xsl:output indent="yes" /> 

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

    <xsl:template match="ns0:Cedent/ns0:Party/ns0:Id[. = '']"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*" /> 
     <xsl:apply-templates select=" 
     ../../following-sibling::ns0:Broker[1]/ns0:Party/ns0:Id/node() 
     " /> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="ns0:Cedent/ns0:Party/ns0:Id/@Agency[. = '']"> 
    <xsl:attribute name="Agency">Legacy</xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 

給你

<Testing xmlns="some_namespace_uri"> 
    <Cedent> 
    <Party> 
     <Id Agency="Legacy">292320710</Id> 
     <Name>Canada</Name> 
    </Party> 
    </Cedent> 
    <Broker> 
    <Party> 
     <Id Agency="Legacy">292320710</Id> 
     <Name>Spain</Name> 
    </Party> 
    </Broker> 
</Testing> 

注:

  • ,如果你不想在輸出中<Broker>元素可言,添加一個空的模板:

    <xsl:template match="ns0:Broker" /> 
    
  • 匹配表達式在模板中不需要從根節點開始。

  • 樣式表的作用是複製輸入只有一些變化,比如這個,應該始終以標識模板開始。
+0

感謝您的優雅的解決方案和解釋。 – JohnXsl 2013-05-04 13:48:25