簡體   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