无法从VBA中的XML文件中获取数据?

时间:2016-06-17 08:54:23

标签: xml vba

我正在尝试从XML文件中获取数据,但无法获取。我不知道我在这里失踪了什么。

XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<TestClass>
  <TestObject>
    <Site>Facebook</Site>
    <Name>ABC</Name>
    <URL>https://www.facebook.com/ABC/</URL>
  </TestObject>
  <TestObject>
    <Site>Facebook</Site>
    <Name>XYZ</Name>
    <URL>https://www.facebook.com/XYZ/</URL>
  </TestObject>
  <TestObject>
    <Site>Twitter</Site>
    <Name>ABC</Name>
    <URL>https://www.twitter.com/ABC/</URL>
  </TestObject>
  <TestObject>
    <Site>Facebook</Site>
    <Name>XYZ</Name>
    <URL>https://www.twitter.com/XYZ/</URL>
  </TestObject>
</TestClass>

代码:

Dim oXMLFile As Object
 Dim XMLFileName As String
 Dim Sites As Object
 Dim Names As Object
 Dim URLs As Object

 Set oXMLFile = CreateObject("Microsoft.XMLDOM")
 XMLFileName = "C:\Users\abc\Desktop\Files\Test.xml"
 oXMLFile.Load (XMLFileName)
 If oXMLFile.Load(XMLFileName) Then
   ' The document successfully to load.
Else
   ' The document failed to load.
End If

Sites = oXMLFile.SelectNodes("TestClass/TestObject/Site/text()")
Names = oXMLFile.SelectNodes("TestClass/TestObject/Name/text()")
URLs = oXMLFile.SelectNodes("TestClass/TestObject/URL/text()")

在上述案例Sites中,NamesURLs一无所获。 enter image description here 如果我在这里遗失任何东西,有人可以建议我吗?

2 个答案:

答案 0 :(得分:1)

由于SitesNamesURLsObject,您需要使用Set关键字。

Set Sites = oXMLFile.SelectNodes("TestClass/TestObject/Site/text()")
Set Names = oXMLFile.SelectNodes("TestClass/TestObject/Name/text()")
Set URLs = oXMLFile.SelectNodes("TestClass/TestObject/URL/text()")

我很惊讶您没有收到错误,但可能是因为Object是特价。

由于SelectNodes返回IXMLDOMNodeList,您可能希望将定义替换为:

Dim oXMLFile as DOMDocument
Dim Sites As IXMLDOMNodeList
Dim Names As IXMLDOMNodeList
Dim URLs As IXMLDOMNodeList

答案 1 :(得分:1)

试试xml linq

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)

        Dim results = doc.Descendants("TestObject").Select(Function(x) New With { _
            .site = CType(x.Element("Site"), String), _
            .name = CType(x.Element("Name"), String), _
            .url = CType(x.Element("URL"), String) _
        }).ToList()
    End Sub

End Module