2014-03-12 30 views
0

存在例如:創建標籤只有當值源

<a> 
<b> 
    <aaa>val</aaa> 
    <bbb></bbb> 
</b> 
</a> 

我想,這將創建AAA,BBB,CCC標記,只有當他們包含源值的XSLT。

到現在爲止我所用:

<aaa><xsl:value-of select="//aaa"/></aaa> 
<bbb><xsl:value-of select="//bbb"/></bbb> 
<ccc><xsl:value-of select="//ccc"/></ccc> 

這顯然是不好的。

+0

一個元素名稱不能以數字開頭,參見例如:http://stackoverflow.com/questions/2087108/encoding -xml-element-name-beginning-with-a-number –

+0

確定這是例子,我將它編輯爲字符 –

+1

XSLT樣式表通常將一個XML轉換爲另一個XML。請編輯您的問題並顯示您的輸入XML和您期望的輸出XML。 –

回答

1

類似於其他的答案,這並未」不依賴於姓名或結構;它只是剝離不包含任何子元素或文本的元素。就像之前提到的那樣,很難說出你實際上在尋找什麼輸出。

XSLT 1.0

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

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

    <xsl:template match="*[not(*|text())]"/> 

</xsl:stylesheet> 

輸出

<a> 
    <b> 
     <aaa>val</aaa> 
    </b> 
</a> 
2

對你想達到什麼做出一些假設(你沒有說得那麼清楚,我很害怕),下面的解決方案應該可以工作。

輸入

<a> 
    <b> 
    <aaa>val</aaa> 
    <bbb></bbb> 
    </b> 
</a> 

樣式表是非常動態的,即不依賴於實際的元素名稱,但是它依賴於XML文檔的結構

樣式表(「動態」)

<?xml version="1.0" encoding="utf-8"?> 

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="xml" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/*|/*/*"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="/*/*/*[not(text())]"/> 
    <xsl:template match="/*/*/*[text()]"> 
     <xsl:copy-of select="."/> 
    </xsl:template> 

</xsl:stylesheet> 

在另一方面,如果該元素的名稱是事先知道的和不改變,你可以在樣式表中使用它們:

樣式表( 「靜態」 的元素名稱)

<?xml version="1.0" encoding="utf-8"?> 

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="xml" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/a|b"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="aaa|bbb"> 
     <xsl:choose> 
      <xsl:when test="text()"> 
       <xsl:copy-of select="."/> 
      </xsl:when> 
      <xsl:otherwise/> 
     </xsl:choose> 
    </xsl:template> 

</xsl:stylesheet> 

輸出

<?xml version="1.0" encoding="UTF-8"?> 
<a> 
    <b> 
     <aaa>val</aaa> 
    </b> 
</a> 
1

您可以創建要忽略的元素的空模板,身份變換模板其他元素:

<xsl:template match="aaa[string-length(text()) = 0]" /> 
<xsl:template match="bbb[string-length(text()) = 0]" /> 

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

不是檢查字符串長度,而是可以將謂詞縮短爲'[not(string())]'。 –

+0

是或'not(text())':) – helderdarocha

+1

True,但用'string()'可以用'替換兩個模板' 。 :-) +1一個很好的答案 –