2017-09-15 136 views
0

如何防止XSLT的默認行爲輸出所有元素?簡單地說,我想忽略所有與我的模板不匹配的元素。XSLT 1.0:忽略模板中所有不匹配的元素

我有下面的XML:

<?xml version="1.0" encoding="UTF-8"?> 
<SDHttpMessage> 
<Headers> 
    <Parameter name="Type">text/xml;charset=UTF-8</Parameter> 
</Headers> 
<Charset>UTF-8</Charset> 
<Message> 
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> 
     <soapenv:Body> 
      <Content> 
       <MyContent> 
        <A>Text A</A> 
        <B>Text B</B> 
        <C>Text C</C> 
       </MyContent> 
      </Content> 
     </soapenv:Body> 
    </soapenv:Envelope> 
</Message> 

而下面的XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
      xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      exclude-result-prefixes="soapenv xsd xsi"> 

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

<xsl:template match="Content/MyContent"> 
    <A><xsl:value-of select="A" /></A> 
    <B><xsl:value-of select="B" /></B> 
    <C><xsl:value-of select="C" /></C> 
</xsl:template> 

所需的輸出:

<A>Text A</A> 
<B>Text B</B> 
<C>Text C</C> 

實際輸出:

text/xml;charset=UTF-8UTF-8 
<A>Text A</A> 
<B>Text B</B> 
<C>Text C</C> 

我想簡單地調用根元素模板中我的模板:

<xsl:template match="/"> 
    <xsl:call-template name="callMyTemplate" /> 
</xsl:template> 

<xsl:template match="Content/MyContent" name="callMyTemplate"> 
    <A><xsl:value-of select="A" /></A> 
    <B><xsl:value-of select="B" /></B> 
    <C><xsl:value-of select="C" /></C> 
</xsl:template> 

但它不匹配任何元素即可。

那麼,如果我只是想忽略所有不匹配的元素,最好的方法是什麼?

在此先感謝。

+0

您確定要輸出一個沒有根元素的XML片段嗎? –

+0

感謝您的評論,我只是想保持樣本儘可能基本 – CoffeeCups

回答

1

你可以添加一個模板來繞過其他分支:

<xsl:template match="/SDHttpMessage"> 
    <xsl:apply-templates select="Message/soapenv:Envelope/soapenv:Body/Content/MyContent"/> 
</xsl:template> 

或覆蓋內置的模板:

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

或者你可以簡單地做:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
exclude-result-prefixes="soapenv"> 
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> 
<xsl:strip-space elements="*" /> 

<xsl:template match="/SDHttpMessage"> 
    <xsl:for-each select="Message/soapenv:Envelope/soapenv:Body/Content/MyContent/*"> 
     <xsl:element name="{name()}"> 
      <xsl:value-of select="." /> 
     </xsl:element> 
    </xsl:for-each> 
</xsl:template> 

</xsl:stylesheet>