2013-03-26 143 views
0

我有一个标签,其中包含标签和文本。获取文本和元素节点使用xpath的节点的子节点

<p> 

Hello world <xref rid='1234'>1234</xref> this is a new world starting 
<xref rid="5678">5678</xref> 
finishing the new world 

</p> 

我打算使用XSLT转换,并在输出我需要更换<xref><a>和文本应具有相同的格式。

<p> 

Hello world <a href='1234'>1234</a> this is a new world starting 
<a href="5678">5678</a> 
finishing the new world 

</p> 
+0

可能重复的必要性://计算器。 COM /问题/ 6112874 /如何更换的-A-标签与-另一个标签功能于XML的使用,XSL) – 2013-03-26 14:40:40

回答

0

的标准方法,以这种在XSLT的事情是身份模板复制一切从逐字输入输出,你当你想改变什么具体的模板,然后覆盖。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <!-- identity template to copy everything as-is unless overridden --> 
    <xsl:template match="*@|node()"> 
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy> 
    </xsl:template> 

    <!-- replace xref with a --> 
    <xsl:template match="xref"> 
    <a><xsl:apply-templates select="@*|node()" /></a> 
    </xsl:template> 

    <!-- replace rid with href --> 
    <xsl:template match="xref/@rid"> 
    <xsl:attribute name="href"><xsl:value-of select="." /></xsl:attribute> 
    </xsl:template> 
</xsl:stylesheet> 

你可以,如果你知道每个xref元素肯定会有一个rid属性的两个“特殊”的模板合并成一个。

请注意,基于XSLT的解决方案不能保留一些事实,即某些输入元素对于属性使用单引号,而其他使用双引号,因为此信息在XPath数据模型中不可用(两种形式就XML解析器而言完全等效)。无论输入元素是什么样子,XSLT处理器可能总是使用其中一个或另一个来输出它输出的所有元素。

0

解决的办法很简单(只有两个模板):

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

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

<xsl:template match="xref"> 
    <a href="{@rid}"><xsl:apply-templates/></a> 
</xsl:template> 
</xsl:stylesheet> 

当这种变换所提供的XML文档应用:

<p> 

Hello world <xref rid='1234'>1234</xref> this is a new world starting 
<xref rid="5678">5678</xref> 
finishing the new world 

</p> 

想要的,正确的结果被生产:

<p> 

Hello world <a href="1234">1234</a> this is a new world starting 
<a href="5678">5678</a> 
finishing the new world 

</p> 

说明

  1. identity rule副本,它被选择用于执行每个节点, “原样”。

    使用
  2. AVT(属性值模板)消除了[如何使用XML XSL另一个标签更换标签(HTTP的xsl:attribute