2017-09-22 79 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>