2012-02-06 119 views
3

所以我有以下XML片段...標籤位置正確的節點的XSLT輸出文本()

我需要把它放到HTML中。我想爲每個(部分)打印出該部分的文本,如果您看到(b)標籤,然後在該單詞周圍輸出該標籤。但我不知道如何做到這一點,因爲它似乎我只能輸出部分的文本()。

但我需要同時輸出節點的text()以及操作該文本()中的標記。

這是樣本XML:

<body> 
<section> 
<title>Response</title> 
<p> Some info here <b> with some other tags</b> or lists like <ol> <li>something</li>  </ol></p> 
</section> 
<section>Another section same format, sections are outputted as divs </section> 
</body> 

這是我到目前爲止有:

<div class="body"> 

<xsl:for-each select='topic/body/section'> 

<div class="section"> 
<xsl:choose> 
<xsl:when test="title"> 
    <h2 class="title sectiontitle"><xsl:value-of select="title"/></h2> 
</xsl:when> 
<xsl:when test="p"> 
    [I dont know what to put here? I need to output both the text of the paragraph tag but also the html tags inside of it..] 
</xsl:when> 
</xsl:choose> 


</div> 
</xsl:for-each> 
</div> 

所需的輸出 - 的HTML代碼塊爲XML中的每個部分。

<div class="section"> 
<h2 class="title">Whatever my title is from the xml tag</h2> 
<p> The text in the paragraph with the proper html tags like <b> and <u> </p> 
</div> 
+1

提供樣本輸入XML和期望的輸出。 – 2012-02-06 13:36:51

+0

一塊代碼請! – TOUDIdel 2012-02-06 13:48:35

回答

2

這很簡單。爲每個要轉換爲HTML的元素編寫一個模板。

所有節點你沒有寫對由身份模板,它們複製到輸出不變的處理模板:

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

<!-- <title> becomes <h2> --> 
<xsl:template match="title"> 
    <h2 class="title"> 
    <xsl:apply-templates select="node() | @*" /> 
    </h2> 
</xsl:template> 

<!-- <section> becomes <div> --> 
<xsl:template match="section"> 
    <div class="section"> 
    <xsl:apply-templates select="node() | @*" /> 
    </div> 
</xsl:template> 

<!-- <b> becomes <strong> --> 
<xsl:template match="b"> 
    <strong> 
    <xsl:apply-templates select="node() | @*" /> 
    </strong> 
</xsl:template> 

的XSLT處理器處理所有的遞歸你(具體地說,<xsl:apply-templates>這是否),讓您的輸入

<section> 
    <title> some text </title> 
    Some stuff there will have other tags like <b> this </b> 
</section> 

會變成

<div class="section"> 
    <h2 class="title"> some text </h2> 
    Some stuff there will have other tags like <strong> this </strong> 
</div> 

由於身份模板不會更改節點,因此您無需編寫「將<ul>變爲<ul>」的模板。這將自行發生。只有不是HTML的元素需要自己的模板。

如果你想防止某些事情不再出現在HTML起來,爲他們寫一個空的模板:

<xsl:template match="some/unwanted/element" /> 
+0

哦,哇,我沒有意識到它會輸出的文字,除非我指定...非常感謝! – Kayla 2012-02-06 14:09:46

+0

@Kayla是的,這是默認設置。除非指定,否則XML元素會輸出它們的「text()」。這是[內置規則之一](http://www.w3.org/TR/xslt#built-in-rule),也在[這裏]描述(http://www.dpawson.co.uk/ XSL/sect2的/ defaultrule.html#d3635e76)。 – Tomalak 2012-02-06 14:16:50

0

<xsl:copy-of select="."/>將輸出的元件的精確副本(而不是<xsl:value-of>這是它的文本值)。

@Tomalak是正確的,但首先有更好的方法來構建您的XSLT。