繁体   English   中英

如何使用XSL使用标签包装XML文本

[英]How can I wrap XML texts with tags using XSL

我想包装文本节点,并使用XSL使用标记构建它们。 下面是一个示例。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <section>
        <container>
            aaa
            <box>
                book
            </box>
            bbb
            <box>
                pen
            </box>
            ccc
            <superscript>
                3
            </superscript>
            ddd
        </container>
    </section>
</root>

是否有可能得到如下所示的结果?

<div>
    <p>aaa</p>
    <div>book</div>
    <p>bbb</p>
    <div>pen</div>
    <p>ccc<span>3</span>ddd</p>
</div>

很高兴您能再帮我一次!

是否有可能得到如下所示的结果?

是。 假设您从复制惯用语开始,则可以添加以下内容:

<xsl:strip-space elements="*"/>

<!-- these we want to turn into a <div> and then process children -->
<xsl:template match="box | container | section | formula">
    <div>
        <xsl:apply-templates />
    </div>
</xsl:template>

<!-- if text node but not directly inside <box> -->
<xsl:template match="text()[not(parent::box)]">
    <p>
        <xsl:value-of select="." />
    </p>
</xsl:template>

<!-- any other text node as-is -->
<xsl:template match="text()">
    <xsl:value-of select="." />
</xsl:template>

注意1:您的示例XML不是有效的XML,但我假设您的意思是</container> ,而不是</formula>

注意2:复制惯用语将复制所有不匹配的内容。 如果您不希望这样做,请将其更改为:

<!-- remove anything we do not need -->
<xsl:template match="node() | @*">
   <xsl:apply-templates />
</xsl:template>

编辑:更正了代码中的一些缺陷。 现在,它会创建以下内容(为便于阅读,增加了空格):

<div>
   <div>
      <p>aaa</p>
      <div>book</div>
      <p>bbb</p>
      <div>pen</div>
      <p>ccc</p>
   </div>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM