gpt4 book ai didi

xslt - 列出 XML 文件中的每个节点

转载 作者:行者123 更新时间:2023-12-01 11:07:20 25 4
gpt4 key购买 nike

简单的情况...对于任何随机的 XML 文件,我想创建一个包含它包含的每个节点的列表,但没有任何重复项!所以像这样:

<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 如何做到这一点?

最佳答案

纯属娱乐,无扩展功能。

<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="'&#xA;'"/>
<xsl:variable name="vPath"
select="concat($pPath,'/',
substring('@',
1 div (count(.|../@*) =
count(../@*))),
name())"/>
<xsl:variable name="vNames">
<xsl:if test="not(contains($pNames,
concat('&#xA;',$vPath,'&#xA;')))">
<xsl:value-of select="concat($vPath,'&#xA;')"/>
</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 行:

string-join(
distinct-values(
(//*|//@*)
/string-join(
(ancestor::node()/name(),
if (self::attribute())
then concat('@',name())
else name()),
'/')),
'&#xA;')

关于xslt - 列出 XML 文件中的每个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com