XSLT - 如何按属性选择 XML 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/541370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XSLT - How to select XML Attribute by Attribute?
提问by phihag
this is the structure of my source xml:
这是我的源 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>
from which I like to create some variables e.g. from all with Value1="2" and all with Value1="5" should result myVar1 with anythingA2 and myVar2 with anythingA5
我喜欢从中创建一些变量,例如从所有的 Value1="2" 和所有的 Value1="5" 应该导致 myVar1 与任何 A2 和 myVar2 与任何 A5
My approch looks like this
我的方法看起来像这样
<xsl:variable name="myVarA" select="/DataSet/Data/[@Value1='2']/@Value2" />
but of course is not working since Value2 is no child of Value1.
但当然不起作用,因为 Value2 不是 Value1 的孩子。
thanks for any hints in advance!
感谢您提前提供任何提示!
回答by phihag
Just remove the slash after Dataand prepend the root:
只需删除后面的斜杠Data并添加根:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
回答by Andrew Hare
There are two problems with your xpath - first you need to remove the child selector from after Datalike phihag mentioned. Also you forgot to include rootin your xpath. Here is what you want to do:
您的 xpath 有两个问题 - 首先,您需要Data像提到的 phihag 一样从 after 中删除子选择器。您也忘记包含root在您的 xpath 中。这是您想要执行的操作:
select="/root/DataSet/Data[@Value1='2']/@Value2"
回答by paul
Try this
尝试这个
xsl:variable name="myVarA" select="//DataSet/Data[@Value1='2']/@Value2" />
The '//' will search for DataSet at any depth
'//' 将在任何深度搜索 DataSet
回答by pixel
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.
注意:在 xpath 的开头使用 // 有点 CPU 密集型 - 它会搜索每个节点以查找匹配项。使用更具体的路径,例如 /root/DataSet 将创建更快的查询。
回答by Stephen Friederichs
I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t
我会通过创建一个变量来实现它,该变量指向在 Value1 中具有正确值的节点,然后引用 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.
其他人的答案也是正确的——事实上更正确,因为我没有注意到你的 XPATH 中额外的斜线会搞砸。尽管如此,这也将有效,并且可能适用于不同的事情,因此请将此方法保留在您的工具箱中。

