XSLT mixed content node

后端 未结 2 1231
余生分开走
余生分开走 2020-12-31 09:40

I have a quite stupid question. How can I make sure that my XML mixed content node doesn\'t get mixed up? I have, say, an XML structure resembling this.

<         


        
相关标签:
2条回答
  • 2020-12-31 10:29

    <xsl:apply-templates> is your friend:

    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    >
      <xsl:output method="html" />
    
      <xsl:template match="root">
        <h1>List of books</h1>
        <xsl:apply-templates />
      </xsl:template>
    
      <!-- a <book> consists of its <title> and <description> -->
      <xsl:template match="book">
        <xsl:apply-templates select="title" />
        <xsl:apply-templates select="description" />
      </xsl:template>
    
      <!-- <title> is turned into a <h2> -->
      <xsl:template match="title">
        <h2>
          <a name="{.}"/>
          <xsl:value-of select="." />
        </h2>
      </xsl:template>
    
      <!-- <description> is turned into a <p> -->
      <xsl:template match="description">
        <p>
          <xsl:apply-templates />
        </p>
      </xsl:template>
    
      <!-- default rule: copy any node beneath <description> -->
      <xsl:template match="description//*">
        <xsl:copy>
          <xsl:copy-of select="@*" />
          <xsl:apply-templates />
        </xsl:copy>
      </xsl:template>
    
      <!-- override rule: <link> nodes get special treatment -->
      <xsl:template match="description//link">
        <a href="#{@ref}">
          <xsl:apply-templates />
        </a>
      </xsl:template>
    
      <!-- default rule: ignore any unspecific text node -->
      <xsl:template match="text()" />
    
      <!-- override rule: copy any text node beneath description -->
      <xsl:template match="description//text()">
        <xsl:copy-of select="." />
      </xsl:template>
    
    </xsl:stylesheet>
    

    The following output is generated for your input XML (Note: I piped it through tidy for the sake of readability. Non-relevant white-space was removed in the process):

    <h1>List of books</h1>
    <h2><a name="Stuff">Stuff</h2>
    <p>This book is <i>great</i> if you need to know about stuff. I
    suggest <a href="#Things">this one</a> if you need to know about
    things.</p>
    
    0 讨论(0)
  • 2020-12-31 10:41
    <root>
     <book>
      <title>Stuff</title>
      <description><![CDATA[
          This book is <i>great</i> if you need to know about stuff.
          I suggest <link ref="Things">this one</link> if you need to know
          about things.
      ]]></description>
     </book>
     [other books]
    </root>
    
    0 讨论(0)
提交回复
热议问题