2017-09-22 77 views
0

我想通過xslt創建一個空文件。xslt - 使用xslt創建空文件1.0

輸入的樣本是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Businessman> 
    <siblings> 
     <sibling>John </sibling> 
    </siblings> 
    <child> Pete </child> 
    <child> Ken </child> 
</Businessman> 

當輸入包含「孩子」標籤的任何存在,它應該產生的文件原樣。當輸入沒有任何'child'標籤時,我需要創建一個空文件(0字節文件)。

這是我的嘗試:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 


<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" /> 
<xsl:template match="@*|node()"> 
    <xsl:choose> 
    <xsl:when test="/Businessman/child"> 
     <xsl:copy> 
     <xsl:apply-templates select="@*|node()" /> 
     </xsl:copy> 
    </xsl:when> 
    </xsl:choose> 
</xsl:template> 
</xsl:stylesheet> 

這使文件不變的時候有任何存在的「孩子」的標籤。但沒有「孩子」標籤時沒有產生任何空文件。

文件我需要測試看起來像:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Businessman> 
    <siblings> 
     <sibling>John </sibling> 
    </siblings> 
</Businessman> 

任何幫助將是巨大的!

感謝

回答

1

處理器去打開輸出文件的麻煩,你必須給它一些東西來寫入輸出文件。嘗試一個空的文本節點。你只需要做出決定「複製與否?」一旦。

<xsl:template match="/"> 
    <xsl:choose> 
    <xsl:when test="/Businessman/child"> 
     <xsl:copy-of select="*"/> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:text/> 
    </xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 

這工作與xsltproc的預期:作出決定只有一次,併產生空的輸出,如果條件不滿足,將用來替換模板

的一種方式。 (如果你發現你自己在包含XML聲明,沒有別的文件,嘗試在XSL調整參數:輸出)

但是,當我發現自己有類似的情況(執行,如果條件C持有該變換,否則...),我只是添加了對會是這個樣子的你的情況文檔節點模板:

<xsl:choose> 
    <xsl:when test="/Businessman/child"> 
    <xsl:apply-templates/> 
    </ 
    <xsl:otherwise> 
    <xsl:message terminate="yes">No children in this input, dying ...</ 
    </ 
</ 

這樣,我得到任何輸出,而不是零長度的輸出。

+0

如何調整xsl:輸出?我嘗試了一些東西 - 但我不斷收到<?xml version =「1.0」encoding =「UTF-8」?>「 –

+0

set'omit-xml-declaration' to'yes' –

0

夠簡單 - 只是不嘗試在一個模板做的一切,不要忘了省略XML聲明,並得到了XPath的權利:如果你想

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" /> 

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

    <xsl:template match="Businessman[child]" priority="9"> 
     <xsl:element name="Businessman"> 
      <xsl:apply-templates /> 
     </xsl:element> 
    </xsl:template> 

    <xsl:template match="Businessman" priority="0" /> 

    <xsl:template match="@* | node()"> 

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