我有我試圖解析XML文件:用或塊對象變量未設置
這是XML文件內容
<MYSTUFF>
<COMPANYNAMES>
<COMPANYNAME>JUMPIN (JIMMY) LIMITED</COMPANYNAME>
<COMPANYNAME>BLADE RUNNER'S TRANSPORT</COMPANYNAME>
<COMPANYNAME>P Griffiths & Sons</COMPANYNAME>
<COMPANYNAME>SOMETIMES, NEVER</COMPANYNAME>
<COMPANYNAME>MASTER/CLASS</COMPANYNAME>
</COMPANYNAMES>
<FIRSTNAMES>
<FIRSTNAME>Richard</FIRSTNAME>
<FIRSTNAME>Jo & hn</FIRSTNAME>
<FIRSTNAME>Paul</FIRSTNAME>
<FIRSTNAME>Geo, rge</FIRSTNAME>
<FIRSTNAME>Ringo</FIRSTNAME>
</FIRSTNAMES>
<LASTNAMES>
<LASTNAME>Davies'</LASTNAME>
<LASTNAME>Lennon</LASTNAME>
<LASTNAME>McCartney(3)</LASTNAME>
<LASTNAME>Harrison</LASTNAME>
<LASTNAME>St/ar</LASTNAME>
</LASTNAMES>
</MYSTUFF>
這是代碼:
Dim XDoc As Object
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.Load (ThisWorkbook.Path & "\test.xml")
'Get Document Elements
Set lists = XDoc.DocumentElement
'Traverse all elements 2 branches deep
For Each listNode In lists.ChildNodes
For Each fieldNode In listNode.ChildNodes
Debug.Print "[" & fieldNode.BaseName & "] = [" & fieldNode.Text & "]"
Next fieldNode
Next listNode
Set XDoc = Nothing
我得到的對象變量或與塊不是設置在這條線上:
For Each listNode In lists.ChildNodes
這是因爲'XDoc.DocumentElement'沒有返回任何內容,可能是因爲'XDoc.Load'無法解析文件。 –
從xml文件中刪除' MASTER/CLASS COMPANYNAME>'和' St/ar '行,然後再試一次 –
jsotola
您的XML文件格式不正確,'&'是[特殊的XML實體](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML),需要轉義爲'&' – Parfait