我有一个 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>
现在:
- 我想要一份所有项目的列表。即使它们是像 A1 中的 A11 这样的子项目,我也想要每个不同的 proj id。
- 此外,我希望在多个地点都可以使用此列表,例如。在解析项目 A1 时,或者在解析 A11 或项目的任何其他嵌套级别时。
有没有办法在 XSLT 中实现这一点?
谢谢。
塔拉·辛格
最佳答案
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.
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(.,'
')"/>
</xsl:for-each>
All Distinct Project IDs:
<xsl:for-each select="$vdistinctProjIds">
<xsl:value-of select="concat(.,'
')"/>
</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
的集合。具有独特的值(value)。
关于xslt - 如何获取 XSLT 中所有出现的相同元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3852333/