26

这是我的源 xml 的结构:

<root>
<DataSet Value="A">
<Data Value1="1" Value2="anythingA1" />
<Data Value1="2" Value2="anythingA2" />
<Data Value1="3" Value2="anythingA3" />
<Data Value1="4" Value2="anythingA4" />
<Data Value1="5" Value2="anythingA5" />
</DataSet>
</root>

我喜欢从中创建一些变量,例如从所有具有 Value1="2" 和所有具有 Value1="5" 的变量应该导致 myVar1 和anyA2 和 myVar2 和anyA5

我的方法看起来像这样

<xsl:variable name="myVarA" select="/DataSet/Data/[@Value1='2']/@Value2" />

但当然不起作用,因为 Value2 不是 Value1 的孩子。

感谢您提前提供任何提示!

4

5 回答 5

48

只需删除斜线Data并在根之前添加:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
于 2009-02-12T14:08:10.017 回答
4

您的 xpath 有两个问题 - 首先您需要从后面Data提到的 phihag 中删除子选择器。你也忘了包含root在你的 xpath 中。这是您想要执行的操作:

select="/root/DataSet/Data[@Value1='2']/@Value2"
于 2009-02-12T14:12:50.020 回答
1

Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.

于 2009-02-12T14:46:54.387 回答
1

尝试这个

xsl:variable name="myVarA" select="//DataSet/Data[@Value1='2']/@Value2" />

'//' 将在任意深度搜索 DataSet

于 2009-02-12T14:16:18.390 回答
0

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

于 2009-02-12T14:35:09.297 回答