2012-02-06 122 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。