简体   繁体   中英

How can I wrap XML texts with tags using XSL

I'd like to wrap text nodes and construct them with tags using XSL. A sample is below.

<?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>

Is it possible to get the result like below?

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

I'm glad if you help me again!

Is it possible to get the result like below?

Yes. Assuming you start with the copy idiom , you can then add the following:

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

Note 1: your example XML is not valid XML, but I assume you meant </container> , not </formula> .

Note 2: the copy idiom will copy everything not matched. If you do not want this, change it to:

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

Edited: corrected a few flaws in the code. It now creates (added space removed for readability) the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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