列出 XML 文件中的每个节点 [英] List every node in an XML file
本文介绍了列出 XML 文件中的每个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单的情况...对于任何随机 XML 文件,我想创建它包含的每个节点的列表,但没有任何重复项!所以就像:
Simple situation... With any random XML file, I want to create a list of every node that it contains, but without any duplicates! So something like:
<root name="example">
<child id="1">
<grandchild/>
</child>
<child id="2"/>
<child id="3"/>
</root>
翻译成:
/root
/root/@name
/root/child
/root/child/@id
/root/child/grandchild
仅使用 XSLT 如何做到这一点?
How to do this, by just using XSLT?
推荐答案
仅供娱乐,无扩展功能.
Just for fun, without extension function.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="text()"/>
<xsl:template match="*|@*">
<xsl:param name="pPath"/>
<xsl:param name="pNames" select="'
'"/>
<xsl:variable name="vPath"
select="concat($pPath,'/',
substring('@',
1 div (count(.|../@*) =
count(../@*))),
name())"/>
<xsl:variable name="vNames">
<xsl:if test="not(contains($pNames,
concat('
',$vPath,'
')))">
<xsl:value-of select="concat($vPath,'
')"/>
</xsl:if>
<xsl:apply-templates select="*[1]|@*">
<xsl:with-param name="pPath" select="$vPath"/>
<xsl:with-param name="pNames" select="$pNames"/>
</xsl:apply-templates>
</xsl:variable>
<xsl:value-of select="$vNames"/>
<xsl:apply-templates select="following-sibling::*[1]">
<xsl:with-param name="pPath" select="$pPath"/>
<xsl:with-param name="pNames" select="concat($pNames,$vNames)"/>
</xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>
输出:
/root
/root/@name
/root/child
/root/child/@id
/root/child/grandchild
编辑:更好的 XSLT/XPath 2.0 示例.此 XPath 2.0 行:
Edit: Better example of XSLT/XPath 2.0. This XPath 2.0 line:
string-join(
distinct-values(
(//*|//@*)
/string-join(
(ancestor::node()/name(),
if (self::attribute())
then concat('@',name())
else name()),
'/')),
'
')
这篇关于列出 XML 文件中的每个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文