2013-03-26 142 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