2013-02-28 80 views
0

刚开始xslt
需要删除元素时,它来空
我做错了什么?
plz帮助
XSLT 1.0:help!无法删除元素

来了一些生成的代码和我尝试去解决问题

我的XSLT:

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

    <!-- 
     The rule represents a custom mapping: "IdSelectFromDate" to 
     "IdSelectFromDate". 
    --> 
    <xsl:template name="IdSelectFromDateToIdSelectFromDate"> 
     <xsl:param name="IdSelectFromDate" /> 
     <!-- ADD CUSTOM CODE HERE. --> 
     <xsl:choose> 
      <xsl:when test="$IdSelectFromDate = ''"> 
       <xsl:copy> 
        <xsl:apply-templates select="IdSelectFromDate" /> 
       </xsl:copy>    
      </xsl:when>  
      <xsl:otherwise> 
       <xsl:value-of select="IdSelectFromDate" /> 
      </xsl:otherwise> 
     </xsl:choose>  
    </xsl:template> 
    <xsl:template match="IdSelectFromDate" /> 
</xsl:stylesheet> 

输入:

<?xml version="1.0" encoding="UTF-8"?> 
<body xmlns:httpsca="http://www.ibm.com/xmlns/prod/websphere/http/sca/6.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="foo.xsd"> 
    <tns:getRealEstateObjects> 
    <RequestElement>   
     <IdNumnet>IdNumnet</IdNumnet> 
     <IdSelectFromDate xsi:nil="true"/> 
    </RequestElement> 
    </tns:getRealEstateObjects> 
</body> 

所需的输出:

<?xml version="1.0" encoding="UTF-8"?> 
    <body xmlns:httpsca="http://www.ibm.com/xmlns/prod/websphere/http/sca/6.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="foo.xsd"> 
     <tns:getRealEstateObjects> 
     <RequestElement>   
      <IdNumnet>IdNumnet</IdNumnet> 

     </RequestElement> 
     </tns:getRealEstateObjects> 
    </body> 
+0

附:删除元素只有在空时 - 否则保留 – Sergey 2013-02-28 12:05:42

+0

您的输入XML不是名称空间良好的形式(它使用未绑定到名称空间URI的'tns'前缀),因此XSLT将遇到麻烦。 – 2013-02-28 12:06:46

+0

上述xslt代码从以下位置调用: <! - 自定义代码的变量 - > ' – Sergey 2013-02-28 12:30:42

回答

1

在这里使用正确的做法是一个身份模板与模板来匹配你要删除的部分:

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

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

    <xsl:template match="IdSelectFromDate[. = '']" /> 
</xsl:stylesheet> 

当你的样品输入运行,这将产生:

<body xsi:noNamespaceSchemaLocation="foo.xsd" 
     xmlns:httpsca="http://www.ibm.com/xmlns/prod/websphere/http/sca/6.1.0" 
     xmlns:tns="..." 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <tns:getRealEstateObjects> 
    <RequestElement> 
     <IdNumnet>IdNumnet</IdNumnet> 
    </RequestElement> 
    </tns:getRealEstateObjects> 
</body>