gpt4 book ai didi

xslt - 如何获取 XSLT 中所有出现的相同元素的值?

转载 作者:行者123 更新时间:2023-12-04 06:44:53 25 4
gpt4 key购买 nike

我有一个 XML 文件,如:

<company>
<dept>
<name> Dept-A</name>
<proj>
<id> A1 </id>
<noOfPeople> 5 </noOfPeople>
<proj>
<id>A11</id>
<noOfPeople> 2 </noOfPeople>
</proj>
</proj>
</dept>
<dept>
....
</dept>
</company>

现在:
  • 我想要一份所有项目的 list 。即使它们是 A1 中的 A11 之类的子项目,我也想要每个不同的项目 ID。
  • 此外,我希望在多个位置提供此列表,例如。在解析项目 A1 时,或在解析 A11 或任何其他嵌套级别的项目时。

  • 有没有办法在 XSLT 中实现这一点?

    谢谢你。
    塔拉·辛格

    最佳答案

    1. I want to have a list of all the projects. Even if they are Sub Projects like A11 inside A1, I want every distinct proj id.

    2. Also, I want to have this list available to me at multiple locations, Ex. While parsing project A1, or while parsing A11 or any other nesting level of proj.

    Is there any way of achieving this in XSLT?



    您尚未指定是否可以拥有多个 <proj>其子元素具有相同值的元素 <id> .

    这是一个 XSLT 解决方案,它定义了两个全局变量 ,所有节点集之一 <id> XML 文档中的元素,另一个 -- <id> 的节点集每个元素的值都不同于其余的值和 <id> 的所有值s 表示。

    由于这些是全局变量,因此可以在 XSLT 代码的任何位置访问它们,即使在导入/包含或导入/包含样式表中也是如此。
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:key name="kIdByVal" match="id" use="."/>

    <xsl:variable name="vallProjIds" select="//proj/id"/>

    <xsl:variable name="vdistinctProjIds" select=
    "//proj/id[generate-id()
    =
    generate-id(key('kIdByVal', .)[1])
    ]
    "/>

    <xsl:template match="/">
    All Project IDs:
    <xsl:for-each select="$vallProjIds">
    <xsl:value-of select="concat(.,'&#xA;')"/>
    </xsl:for-each>
    All Distinct Project IDs:
    <xsl:for-each select="$vdistinctProjIds">
    <xsl:value-of select="concat(.,'&#xA;')"/>
    </xsl:for-each>
    </xsl:template>
    </xsl:stylesheet>

    当此转换应用于以下 XML 文档时 (基于提供的一个,但格式良好并扩展到涵盖更多情况):
    <company>
    <dept>
    <name> Dept-A</name>
    <proj>
    <id> A1 </id>
    <noOfPeople> 5 </noOfPeople>
    <proj>
    <id>A11</id>
    <noOfPeople> 2 </noOfPeople>
    </proj>
    </proj>
    </dept>
    <dept>
    <name> Dept-B</name>
    <proj>
    <id> A1 </id>
    <noOfPeople> 5 </noOfPeople>
    </proj>
    <proj>
    <id> B1 </id>
    <noOfPeople> 5 </noOfPeople>
    <proj>
    <id>B11</id>
    <noOfPeople> 2 </noOfPeople>
    </proj>
    </proj>
    </dept>
    </company>

    产生了想要的、正确的结果 :
      All Project IDs:
    A1
    A11
    A1
    B1
    B11

    All Distinct Project IDs:
    A1
    A11
    B1
    B11

    请注意 该解决方案使用Muenchian方法进行分组以获得 Id的集合s 具有唯一值。

    关于xslt - 如何获取 XSLT 中所有出现的相同元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3852333/

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