简体   繁体   English

使用 Excel VBA 读取 XML

[英]Reading XML with Excel VBA

I'm trying to essentially obtain the "Rate" value in the below XML using VBA (this is a much shortened version, the actual has over 500 rates to choose from).我正在尝试使用 VBA 在下面的 XML 中获得“费率”值(这是一个大大缩短的版本,实际有 500 多种费率可供选择)。 I'm struggling to get to it without having to cycle through every single node till I reach the right one.我正在努力实现它,而不必遍历每个节点,直到找到正确的节点。

-<DC>
- <Overviews>
      - <OverviewCurve>
         <Identifier>zero_libor_usd</Identifier>
         - <Curve>
           - <YieldCurve>
               - <Node>
                   <Term>32</Term> 
                   <Rate>0.027613082673910938</Rate> 
                 </Node>
            </YieldCurve>
          </Curve>
       </OverviewCurve>
 </Overviews>
</DC>

The code I am attempting to use is..我试图使用的代码是..

Set xmldoc = New MSXML2.DOMDocument60
xmldoc.async = False
xmldoc.Load (Range("Path").Value & Range("FileName").Value)
Set xmlNode2 =xmldoc.SelectSingleNode("/DC/Overviews/OverviewCurve/Identifier/Curve/YieldCurve/Node/Rate")

But the code returns "Nothing" for xmlNode2.但是代码为 xmlNode2 返回“Nothing”。 The xml file itself essentially has 5 other "OverviewCurve" nodes all structured in the same way with 50 "rate" nodes (ie 50 "term" nodes). xml 文件本身基本上有 5 个其他“OverviewCurve”节点,所有节点都以相同的方式构建,其中包含 50 个“rate”节点(即 50 个“term”节点)。 I'm trying to obtain each of these from the file.我试图从文件中获取每一个。 I've removed some other nodes that are child to the "Overviews" node as they are not relevant for what I am trying to extract.我已经删除了一些其他节点,它们是“概述”节点的子节点,因为它们与我试图提取的内容无关。

If there are multiple Rate nodes, then the XPATH "/DC/Overviews/OverviewCurve/Identifier/Curve/YieldCurve/Node/Rate" will not be a SingleNode .如果有多个Rate节点,那么XPATH "/DC/Overviews/OverviewCurve/Identifier/Curve/YieldCurve/Node/Rate" 将不是SingleNode

Example例子

 Dim xmlDoc As MSXML2.DOMDocument60
 Dim xmlNode As MSXML2.IXMLDOMNode
 Dim xmlNodeList As MSXML2.IXMLDOMNodeList

 Set xmlDoc = New MSXML2.DOMDocument60
 xmlDoc.async = False
 xmlDoc.Load "P:\test.xml"

 Set xmlNode = xmlDoc.SelectSingleNode("//Rate[1]") 'xmlNode is now the first Rate

 Set xmlNodeList = xmlDoc.SelectNodes("//Rate") 'xmlNodeList is now a list of all Rate nodes

The syntax is XPATH see https://en.wikipedia.org/wiki/XPath .语法是XPATH请参阅https://en.wikipedia.org/wiki/XPath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM