XSLT或XPath:如何查找带有特定标签和文本的节点,然后将其提取到新的xml文件中? [英] XSLT or XPath: how to find a node with a specific tag and text then extract it into a new xml file?
本文介绍了XSLT或XPath:如何查找带有特定标签和文本的节点,然后将其提取到新的xml文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在xml文件<example>Some text</example>
然后,我想从xml文件中提取该节点及其子元素,并将其写入新的xml文件中,然后我需要提取原始xml文件中的其他剩余xml节点,减去提取的节点到新的xml文件中.跟随提取的节点.
Then I want to extract this node and it's subelements from the xml file and write it into a new xml file and I then need to extract the other remaining xml nodes in the original xml file minus the extracted node into the new xml file following the extracted node.
如何使用xslt或xpath做到这一点?
How can I do this with xslt or 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>
这篇关于XSLT或XPath:如何查找带有特定标签和文本的节点,然后将其提取到新的xml文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文