使用VBA查询xml属性值并将其parsing为XLS
我试图打开/加载在B2
范围内的Excel工作表中指定的XML文件。 然后,searchname=FUNCTIONAL_ITEM
的XML属性列表,并获取">
后的所有属性值。
在下面的例子中,我想提取出值8
和10
。
<Attribute name="BIN" dataType="String" unit="" multiplier="" tag="LINE,MRPM">1</Attribute> <Attribute name="FUNCTIONAL_ITEM" dataType="Double" unit="" multiplier="" tag="LINE,LINE DB">8</Attribute> <Attribute name="FUNCTIONAL_ITEM" dataType="Double" unit="" multiplier="" tag="LINE,LINE DB">9</Attribute> <Attribute name="FUNCTIONAL_ITEM" dataType="Double" unit="" multiplier="" tag="LINE,LINE DB">10</Attribute>
有人可以指出我正确的方向来实现这一点。
你需要使用的是XPath。 假设你有一个DomDocument60
对象中的XML文档,我们将调用d
并且你已经声明了一个名为i
的IXMLDOMNodeList
variables,那么使用下面的代码:
Set i = d.selectNodes("//Attribute[@name='FUNCTIONAL ITEM']")
然后,您可以遍历i
的节点并从每个节点提取text
属性。
这是一个相当简单的程序来演示(如果你还没有这样做的话,你需要通过Tools> References添加一个对“Microsoft XML,v6.0”的引用):
Sub main() Dim d As DOMDocument60 Dim i As IXMLDOMNodeList Dim n As IXMLDOMNode Set d = New DOMDocument60 d.Load 'file path goes here Debug.Print "*****" Set i = d.selectNodes("//Attribute[@name='FUNCTIONAL ITEM']") For Each n In i Debug.Print n.Text Next n Debug.Print "*****" End Sub