gpt4 book ai didi

xml - XSLT:如何获取所有子节点中特定节点的位置索引

转载 作者:数据小太阳 更新时间:2023-10-29 02:22:00 24 4
gpt4 key购买 nike

考虑以下 XML:

<root>
<a>
<pos>
<c val="abc"></c>
<c val="def"></c>
<c val="ghi"></c>
<c val="jkl"></c>
<c val="mno"></c>
</pos>
<b>
<c></c>
</b>
<b>
<c></c>
<d>here</d>
</b>
<b>
<e>and</e>
<c></c>
<d>for</d>
</b>
<b>
<c></c>
<c></c>
<d>also</d>
</b>
</a>
<a>
<pos>
<c val="pqr"></c>
<c val="stu"></c>
<c val="vwx"></c>
<c val="yz"></c>
</pos>
<b>
<c></c>
<d>what</d>
</b>
<b>
<c></c>
</b>
<b>
<d>how</d>
</b>
<b>
<c></c>
<d>where</d>
<c></c>
</b>
</a>
</root>

现在在我的输出中,每当我遇到 <c></c>b 里面, 我需要把 val 对应的值<c></c> 的属性来自 <pos></pos>节点。相应的值是指节点的索引 c里面pos应与 c 的索引相同在所有b节点合并。

期望的输出是:

<start>
<level>
abc
</level>
<level>
def
here
</level>
<level>
and
ghi
for
</level>
<level>
jkl
mno
also
</level>
<start>


<start>
<level>
pqr
what
</level>
<level>
stu
</level>
<level>
how
</level>
<level>
vwx
where
yz
</level>
</start>

我尝试使用以下 XSL:

<xsl:template match="root">
<star>
<xsl:apply-templates select="a"/>
</start>
</xsl:template>
<xsl:template match="a">
<xsl:apply-templates select="b"/>
</xsl:template>
<xsl:template match="b">
<level>
<xsl:for-each select="*">
<xsl:choose>
<xsl:when test="name() = 'd'">
<xsl:value-of select="."/>
</xsl:when>
<xsl:when test="name() = 'e'">
<xsl:value-of select="."/>
</xsl:when>
<xsl:when test="name() = 'c'">
<xsl:variable name="posCount">
<!-- I don't know what to do here -->
</xsl:valiable>
<xsl:for-each select="ancestor::a[1]/pos">
<xsl:for-each select="c[position() = $posCount]">
<xsl:value-of select="@val"/>
</xsl:for-each>
</xsl:for-each>

</xsl:when>
</xsl:choose>
</xsl:for-each>
</level>
</xsl:template>

我需要做的是以某种方式获取每个 c 的位置计数里面所有b s 合并,然后使用 val 的值对应定位的属性c从里面pos .

我怎样才能继续这样做?

注意:我使用的是 XSLT 1.0

提前致谢!

最佳答案

使用 xsl:number 元素可以很容易地获得您要查找的索引号。例如:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="root">
<root>
<xsl:apply-templates select="a"/>
</root>
</xsl:template>

<xsl:template match="a">
<start>
<xsl:apply-templates select="b"/>
</start>
</xsl:template>

<xsl:template match="b">
<level>
<xsl:text>&#10;</xsl:text>
<xsl:apply-templates select="*"/>
</level>
</xsl:template>

<xsl:template match="d|e">
<xsl:value-of select="."/>
<xsl:text>&#10;</xsl:text>
</xsl:template>

<xsl:template match="b/c">
<xsl:variable name="i">
<xsl:number count="b/c" from="a" level="any" />
</xsl:variable>
<xsl:value-of select="ancestor::a/pos/c[number($i)]/@val"/>
<xsl:text>&#10;</xsl:text>
</xsl:template>

</xsl:stylesheet>

注意事项:
1. 我在输出中添加了一个 root 元素,使其成为有效的 XML;
2. 最好用一个keypos/c中获取对应的值。

关于xml - XSLT:如何获取所有子节点中特定节点的位置索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22111347/

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