2013-03-11 47 views
0

我需要將<math>元素組合並僅輸出<math>元素。我嘗試在XSLT下面。 請注意,元素可以出現在文檔中的任何地方,並且還根元素還可以改變使用XSLT1.0的組元素

XSLT 1.0嘗試:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:m="http://www.w3.org/1998/Math/MathML"> 
<xsl:key name="aKey" match="m:math" use="."/> 

<xsl:template match="node()"> 
<xsl:copy-of select="key('aKey',m:math)"/> 
</xsl:template> 
</xsl:stylesheet> 

示例XML:

<?xml version="1.0"?> 
<chapter xmlns:m="http://www.w3.org/1998/Math/MathML"> 
<p>This is sample text 
<a><math>This is math</math></a></p> 
<a>This is a</a> 
<math>This is math</math> 
<a>This is a</a> 
<a>This is a</a> 
<b>This is <math>This is math</math>b</b> 
<c>This is C</c> 
</chapter> 

輸出所需:

<math>This is math</math> 
<math>This is math</math> 
<math>This is math</math> 

回答

0

這將做到這一點:

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

    <xsl:template match="math | math//*" priority="2"> 
    <xsl:element name="{name()}"> 
     <xsl:apply-templates select="@* | node()" /> 
    </xsl:element> 
    </xsl:template> 

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

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

當你的樣品輸入運行,這將產生:

<math>This is math</math> 
<math>This is math</math> 
<math>This is math</math> 

使用密鑰的一種方法,其產生相同的輸出:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes" /> 
    <xsl:key name="kMath" match="math" use="''" /> 

    <xsl:template match="/"> 
    <xsl:apply-templates select="key('kMath', '')" /> 
    </xsl:template> 

    <xsl:template match="*"> 
    <xsl:element name="{name()}"> 
     <xsl:apply-templates select="@* | node()" /> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="@* | node()" priority="-2"> 
    <xsl:copy /> 
    </xsl:template> 
</xsl:stylesheet> 
+0

我通過嘗試關鍵,是否有可能? – siva2012 2013-03-11 13:40:07

+0

是的,這是可能的。我已經在上面添加了一個例子,但我不認爲在這裏使用密鑰的確是一個很好的理由。 – JLRishe 2013-03-11 13:52:21

+0

感謝您的快速回復,我會檢查並更新 – siva2012 2013-03-11 14:02:13