如何将 XML 个元素转换为文本

How to convert XML elements to text

请建议如何将 XML 元素及其 namecontent 转换为转义文本(即 <a>&lt;a&gt;).

XML:

<article>
      <a>
           <b>a<c>a</c>aa</b> the remaining text</a>
</article>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" version="1.0" encoding="utf-8"/>

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

     <xsl:template match="a">
          <xsl:element name="new">
              <xsl:attribute name="attrib1">
                  <xsl:for-each select="descendant-or-self::*">
                       <xsl:text>&lt;</xsl:text><xsl:value-of select="name()"/><xsl:text>&gt;</xsl:text>
                            <xsl:value-of select="."/>
                       <xsl:text>&lt;/</xsl:text><xsl:value-of select="name()"/><xsl:text>&gt;</xsl:text>
                  </xsl:for-each>
             </xsl:attribute>
         </xsl:element>
     </xsl:template>

</xsl:stylesheet>

要求输出:

<article><new attrib1="&lt;a&gt; &lt;b&gt;a&lt;c&gt;a&lt;/c&gt;aa&lt;/b&gt; the remaining text&lt;/a&gt;"/></article>

以下 XSLT 1.0 样式表(也与 XSLT 2.0 兼容):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="utf-8" omit-xml-declaration="yes"/>

  <xsl:template match="article">
    <xsl:copy>
      <new>
        <xsl:attribute name="attrib1">
          <xsl:apply-templates/>
        </xsl:attribute>
      </new>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="normalize-space(.)"/>
  </xsl:template>

  <xsl:template match="*">
    <xsl:text disable-output-escaping="yes">&lt;</xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:text disable-output-escaping="yes">&gt;</xsl:text>
    <xsl:apply-templates/>
    <xsl:text>&lt;/</xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:text>&gt;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

已应用于您的输入 XML:

<article>
      <a>
           <b>a<c>a</c>aa</b> the remaining text</a>
</article>

产生此输出 XML:

<article><new attrib1="&lt;a&gt;&lt;b&gt;a&lt;c&gt;a&lt;/c&gt;aa&lt;/b&gt;the remaining text&lt;/a&gt;"/></article>

根据要求。