如何在xml文档中保留所有标记,结构和文本,仅替换某些XSLT?

sni*_*tko 3 xml xslt xml-parsing

我一直在尝试将简单的xsl样式应用于xml文档:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <html>
      <body>

        <xsl:for-each select="//title">
          <h1><xsl:value-of select="."/></h1>
        </xsl:for-each>

      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

不幸的是,这似乎只是简单地忽略所有其他标签并从输出中删除它们以及它们的内容,而我只留下转换为h1s的标题.我希望能够做的是保留我的文档结构,同时只替换它的一些标签.

所以,例如,如果我有这个文件:

<section>
  <title>Hello world</title>
  <p>Hello!</p>
</section>
Run Code Online (Sandbox Code Playgroud)

我可以得到这个:

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>
Run Code Online (Sandbox Code Playgroud)

不太确定在XSLT手册中的哪个地方开始寻找.

JLR*_*she 7

正如OR Mapper所说,解决方案是在转换中添加一个标识模板,然后覆盖您需要的部分.这将是完整的解决方案:

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

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

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

  <xsl:template match="title">
    <h1>
      <xsl:apply-templates select="@* |node()" />
    </h1>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

在样本输入上运行时,会产生:

<html>
  <body>
    <section>
      <h1>Hello world</h1>
      <p>Hello!</p>
    </section>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果你真的只想保留你的原始XML但是替换它<title>,你可以删除中间<xsl:template>,你应该得到结果:

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>
Run Code Online (Sandbox Code Playgroud)