VBA 按属性选择 XML 节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18064052/
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
VBA select XML node by attribute
提问by Jesse
I've been searching SO (and the rest of the Internet) for the answer, but I can't seem to find a solution for selecting an XML node based on an attribute.
我一直在搜索 SO(以及互联网的其余部分)以寻找答案,但我似乎无法找到基于属性选择 XML 节点的解决方案。
Example XML:
示例 XML:
<foo>
<bar name="do">A</bar>
<bar name="rae">B</bar>
<bar name ="mi">C</bar>
</foo>
So if I want to get B
by the rae
value of the name
attribute, I've tried:
所以如果我想B
通过属性的rae
值来获取name
,我已经尝试过:
myValue = myXML.selectSingleNode("//foo/bar/").Attributes.getNamedItem("rae").Text
Thanks!
谢谢!
回答by Jesse
The solution that ended up working for me is:
最终对我来说有效的解决方案是:
myValue = myXML.selectSingleNode("var[@name='ID']").Text
回答by APrough
Using your example...
用你的例子...
myValue = myXML.SelectSingleNode("/foo/bar[@name='rae']").InnerXML
Note the use of the @ in the variable name. Your criteria (everything between the square brackets) goes on the level that you are searching through.
注意变量名中@的使用。您的标准(方括号之间的所有内容)取决于您正在搜索的级别。
回答by Jaycal
If there are multiple nodes, then I don't think you'd be able to use SelectSingleNode
. Instead, you can use XPathand getElementsByTagName. In addition, (though it may not be necessary in your case) to ensure that you're only getting one node, you can use NextNode
. The final code using your sample XML would be...
如果有多个节点,那么我认为您无法使用SelectSingleNode
. 相反,您可以使用XPath和 getElementsByTagName。此外,(尽管在您的情况下可能没有必要)确保您只获得一个节点,您可以使用NextNode
. 使用您的示例 XML 的最终代码将是...
myValue = myXML.getElementsByTagName("/foo[@name='rae']/bar").nextNode.nodeTypedValue