我正在尝试从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()")
答案 0 :(得分:1)
由于Sites
,Names
和URLs
为Object
,您需要使用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