我需要在 xml 文件中找到一个特定的节点,<example>Some text</example>
然后我想从 xml 文件中提取这个节点及其子元素并将其写入一个新的 xml 文件,然后我需要将原始 xml 文件中的其他剩余 xml 节点减去提取的节点提取到新的 xml 文件中。节点。
如何使用 xslt 或 xpath 执行此操作?
以下是如何输出所有节点减去特定节点及其子树:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="example[. = 'Some text']"/>
</xsl:stylesheet>
当此转换应用于以下 XML 文档时(未提供!):
<a>
<example>Some different text</example>
<b>
<c>
<example>Some text</example>
</c>
<example>Some other text</example>
</b>
</a>
产生了想要的正确结果:
<a>
<b>
<c></c>
</b>
</a>
以下是仅提取所需节点及其子树的方法:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="example[. = 'Some text']">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当应用于同一个 XML 文档(上图)时,现在的结果是:
<example>Some text</example>
不能在单个 XSLT 1.0 转换中生成两个不同的结果文档。
这是一个 XSLT 2.0 转换,它输出第一个结果并将第二个结果写入文件:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vResult2">
<xsl:apply-templates mode="result2"/>
</xsl:variable>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="example[. = 'Some text']"/>
<xsl:template match="/">
<xsl:apply-templates/>
<xsl:result-document href="file:///c:/temp/delete/result2.xml">
<xsl:sequence select="$vResult2"/>
</xsl:result-document>
</xsl:template>
<xsl:template mode="result2" match="example[. = 'Some text']">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template mode="result2" match="text()"/>
</xsl:stylesheet>