2016-05-29 84 views
0

我想使用xslt從xml文件的元素中選擇一些具有特定值的節點集。我確實得到了我想要的節點,但我也從textnodes中獲得了一些序列化的文本。 你能幫我擺脫這段文字嗎?爲什麼文本節點出現在轉換後的xml中

這是源文件:

<surveys> 
<survey id='01'> 
    <category>cat1</category> 
    <questions> 
     <question id='1'>Y</question> 
     <question id='2'>Y</question> 
     <question id='3'>Y</question> 
     <question id='4'>Y</question> 
    </questions> 
</survey> 
<survey id='02'> 
    <category>cat2</category> 
    <questions> 
     <question id='1'>Y</question> 
     <question id='2'>Y</question> 
     <question id='3'>N</question> 
     <question id='4'>N</question> 
    </questions> 
</survey> 
<survey id='03'> 
    <category>cat1</category> 
    <questions> 
     <question id='1'>N</question> 
     <question id='2'>N</question> 
     <question id='3'>N</question> 
     <question id='4'>N</question> 
    </questions> 
</survey> 
<survey id='04'> 
    <category>cat3</category> 
    <questions> 
     <question id='1'>N</question> 
     <question id='2'>N</question> 
     <question id='3'>Y</question> 
     <question id='4'>Y</question> 
    </questions> 
</survey> 
</surveys> 

這是轉換文件:

<?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" omit-xml-declaration="yes" indent="yes"/> 

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

<xsl:template match="survey[category = 'cat2']"> 
    <xsl:copy-of select="."/> 
</xsl:template> 

</xsl:stylesheet> 

而這個結果:

<surveys>cat1YYYY<survey id="02"> 
    <category>cat2</category> 
    <questions> 
     <question id="1">Y</question> 
     <question id="2">Y</question> 
     <question id="3">N</question> 
     <question id="4">N</question> 
    </questions> 
</survey>cat1NNNNcat3NNYY</surveys> 

所以,我想獲得在調查元素後面的第一行中刪除「cat1YYYY」,在調查元素後面的最後一行中刪除「cat1NNNNcat3NNYY」。 我想了解爲什麼它的存在;-)

回答

2

我想了解爲什麼它的存在

它的存在,因爲你不加選擇地應用模板 - 和XSLT有一些built-in template rules是複製文本節點爲默認值。

爲了防止這種情況發生,你可以添加自己的模板來覆蓋缺省行爲:

<xsl:template match="text()" /> 

或 - 最好 - 選擇套用模板開始:

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

<xsl:template match="/surveys"> 
    <surveys> 
     <category/> 
     <xsl:apply-templates select="survey[category = 'cat2']"/> 
    </surveys> 
</xsl:template> 

<xsl:template match="survey"> 
    <xsl:copy-of select="."/> 
</xsl:template> 

</xsl:stylesheet> 

這BTW可能縮寫爲:

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

<xsl:template match="/surveys"> 
    <surveys> 
     <category/> 
     <xsl:copy-of select="survey[category = 'cat2']"/> 
    </surveys> 
</xsl:template> 

</xsl:stylesheet> 
0

您可以發送多餘text()節點被遺忘加入

<xsl:template match="text()" /> 

到您的樣式表。