2017-02-20 88 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。谢谢,这工作。 –