1

也许有人有类似的问题。我需要使用 XSL 转换输入 XML 文件:

<decision>
    <akapit nr = 1>
           This is <b>important</b> decision for the query number <i>0123456</i>
    </akapit>
</decision>

作为输出,我需要一个 html 文档,它将元素中的文本显示<b></b>为粗体,元素显示<i></i>为斜体......等等。所以,基本上我需要<akapit>根据子元素的名称来格式化来自 XML 元素的输出 HTML。知道在这种情况下如何使用 XSL 模板吗?

4

3 回答 3

2

解决此类问题的基本方法是

<xsl:template match="akapit">
  <div>
   <xsl:copy-of select="node()"/>
  </div>
</xsl:template>

只要 XML 输入使用与 HTML 使用的相同元素(例如粗体或斜体),这就足够了。

如果输入 XML 中有其他元素,例如

<decision>
    <akapit nr = 1>
           This is <bold>important</bold> decision for the query number <i>0123456</i>
    </akapit>
</decision>

那么你需要转换东西,例如

<xsl:template match="akapit">
  <div>
    <xsl:apply-templates/>
  </div>
</xsl:template>

<xsl:template match="akapit//*">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="akapit//bold">
  <b>
    <xsl:apply-templates/>
  </b>
</xsl:template>
于 2012-09-26T09:28:04.107 回答
1

In case the markup elements names aren't the same as the corresponding Html element names, for example:

<decision>
    <akapit nr="1">
    This is 
        <bold>important</bold> decision for the query number
        <italic>0123456</italic>
    </akapit>
</decision>

Then a very simple application of the identity rule is this:

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

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

 <xsl:template match="akapit">
  <div><xsl:apply-templates/></div>
 </xsl:template>

 <xsl:template match="bold"><b><xsl:apply-templates/></b></xsl:template>
 <xsl:template match="italic"><i><xsl:apply-templates/></i></xsl:template>

 <xsl:template match="/*"><xsl:apply-templates/></xsl:template>
</xsl:stylesheet>

And when this transformation is applied on the above XML document, the wanted, correct result is produced:

<div>
    This is 
        <b>important</b> decision for the query number
        <i>0123456</i>
</div>

Do Note: Using xsl:apply-templates should be preferred to xsl:copy-of as the latter doesn't allow flexibility to further process the selected nodes -- it only copies them.

于 2012-09-26T12:51:12.860 回答
0

如果我理解正确,您可以使用copy-of复制akapit元素下的所有内容。

<xsl:template match="/decision/akapit[@nr='1']">
    <xsl:copy-of select="child::node()"/>
</xsl:template>
于 2012-09-26T09:33:44.277 回答