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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:34:13  来源:igfitidea点击:

VBA select XML node by attribute

xmlvbaexcel-vbaxml-parsingexcel

提问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 Bby the raevalue of the nameattribute, 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