0

我有这样的事情:

<body>
    foo bar foo bar foo bar...
    <p>foo bar!</p>
    <div class="iWantYourContent">
        <p>baz</p>
    </div>
</body>

我想要这个输出:

<body>
    foo bar foo bar foo bar...
    <p>foo bar!</p>
    <p>baz</p>
</body>

我已经设法使用以下方法获取节点的内容:

<xsl:template match="/">
        <xsl:apply-templates select="//x:div[@class = 'iWantYourContent']"/>
</xsl:template>

<xsl:template match="//x:div[@class = 'iWantYourContent']">
    <body>
        <xsl:copy-of select="node()"/>
    </body>
</xsl:template>

但我无法保留文件的其余部分。

感谢您的帮助。

4

2 回答 2

4

做这种事情的方法通常是使用复制所有内容的身份模板:

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

然后你制作一个模板来匹配你想要跳过的项目:

<xsl:template match="div[@class='iWantYourContent']" >
   <xsl:apply-templates select="*" />
</xsl:template>

即跳过副本,因为您不希望复制 div 元素,但请在其他元素上应用模板,因为您确实想要复制 div 的后代。

(如果您想完全跳过内容,那么您将模板留空并且根本没有内容输出。)

于 2013-09-04T15:17:47.473 回答
0

如果您只对纯文本和<p>节点感兴趣,请使用:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- Suppress the xml header in output -->
  <xsl:output method="html" omit-xml-declaration="yes" />

  <xsl:template match="/">
    <body><xsl:apply-templates /></body>
  </xsl:template>

  <xsl:template match="p">
      <p><xsl:copy-of select="text()"/></p>
  </xsl:template>
</xsl:stylesheet>

我使用命令行工具xsltproc来测试样式表:

xsltproc test.xsl test.html

输出:

<body>
    foo bar foo bar foo bar...
    <p>foo bar!</p>

        <p>baz</p>

</body>
于 2013-09-04T15:18:08.010 回答