2017-02-20 50 views
0

我是新來的XSLT,我試圖將XML轉換:XSLT樣式表來選擇特定的子元素

`<xml> 
    <id1>1</id1> 
    <id2>2</id2> 
    <abc> 
     <a>a</a> 
     <b>b</b> 
     <c>c</c> 
    </abc> 
</xml>` 

另一個XML:

`<xml> 
    <id1>1</id1> 
    <abc> 
     <a>a</a> 
     <b>b</b> 
    </abc> 
</xml>` 

我可以使用什麼樣式表來實現這一目標?

轉換規則: id1,abc/a和abc/b元素將被保留。所有其他因素都將被忽略,也就是說,我有一組特定的元素,我希望保留而忽略所有其他元素。

+0

一個例子是不夠的;請解釋轉換的**規則**。 –

+0

@ michael.hor257k。謝謝添加規則 –

回答

0

如果你有節點的「白」名單,以保持,那麼最簡單的方法來實現它是通過使用它來選擇性地應用模板:

XSLT 1.0

<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:strip-space elements="*"/> 

<!-- identity transform --> 
<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="/xml"> 
    <xsl:copy> 
     <xsl:apply-templates select="id1 | abc"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="abc"> 
    <xsl:copy> 
     <xsl:apply-templates select="a | b"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

或者,如果你願意:

<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:strip-space elements="*"/> 

<xsl:template match="/xml"> 
    <xsl:copy> 
     <xsl:copy-of select="id1"/> 
     <xsl:apply-templates select="abc"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="abc"> 
    <xsl:copy> 
     <xsl:copy-of select="a | b"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

@ michael.hor257k。謝謝,這工作。 –