0

我正在尝试创建一个样式表以将<body>元素复制到输出并隐式删除所有其他元素。

资源:

<!-- language: lang-xml -->
<?xml version="1.0" encoding="UTF-8"?>
<document>
    <info>trial</info>
    <style>unknown</style>
    <body>
        <section>
            <p>para 1</p>
            <p>para 2</p>
        </section>
    </body>
</document>

期望的输出:

<!-- language: lang-xml -->
<?xml version="1.0" encoding="UTF-8"?>
<document>
    <body>
        <section>
            <p>para 1</p>
            <p>para 2</p>
        </section>
    </body>
</document>

XSLT:

<!-- language: lang-xsl -->
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>

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

    <xsl:template match="node()[not(descendant-or-self::body)]"/>

</xsl:stylesheet>

上述 XSLT 的输出:

<!-- language: lang-xml -->
<?xml version="1.0" encoding="UTF-8"?>
<document>
    <body/>
</document>

Ps 我是 XSLT 的新手。如果您能解释您的解决方案并为我指出一个合适的资源来学习 xpath 和 xslt 1.0,那将是一个救命稻草!

4

2 回答 2

1

好吧,section没有body后代,因此它与您的模板匹配并被删除。您可能打算写[not(ancestor-or-self::body)]- 但这也将包括 root document,因此结果将为空。为什么不简单地做:

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

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

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

</xsl:stylesheet>

甚至更简单:

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

<xsl:template match="/document">
    <xsl:copy>
        <xsl:copy-of select="body"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
于 2020-04-23T18:57:00.057 回答
0

这是你可以做到的。我在评论中提出了一些提示/解释。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="document">
      <xsl:copy> <!-- copy the current node (not its content) -->
          <xsl:apply-templates select="body"/> <!-- Apply templates to selected node -->
      </xsl:copy>
  </xsl:template>

  <!-- Identity template. Ref : https://en.wikipedia.org/wiki/Identity_transform -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

看到它在这里工作:https ://xsltfiddle.liberty-development.net/bEzknsS

于 2020-04-23T18:58:46.257 回答