在vba中访问XML节点属性

时间:2017-10-11 06:31:46

标签: xml excel vba excel-vba

我想只访问属性类型=“file”的节点,我怎么能用vba

<?xml version="1.0" encoding="utf-8"?>
<Metrics>
<!--Note: This report is generated using the software (PRQA Framework) of 
Programming Research Limited and is the Intellectual Property of Programming 
Research Limited-->
<File name="C:/File.c">
<Entity name="File.c" type="file">

1 个答案:

答案 0 :(得分:0)

这是一些有效的代码。您必须在VBA IDE的工具菜单中添加对Microsoft XML v6.0的引用才能使其正常运行。

Sub SOExample()
    'Made some changes here to make this valid XML
    'This was missing some closing tags for file and entity
    Const XML As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
                           "<Metrics>" & _
                           "<File name=""C:/File.c""></File>" & _
                           "<Entity name=""File.c"" type=""file""></Entity>" & _
                           "</Metrics>"

    Dim xmlDoc As DOMDocument60: Set xmlDoc = New DOMDocument60
    xmlDoc.LoadXML XML

    Dim ele  As IXMLDOMNode
    Dim eles As IXMLDOMNodeList: Set eles = xmlDoc.getElementsByTagName("*")

    'Iterate each element and test to see if the name is File
    For Each ele In eles
        If ele.BaseName = "File" Then
            'Print out the nodeName and the value
            Debug.Print ele.nodeName, ele.Attributes(0).NodeValue
        End If
    Next

End Sub