我有一个简单的XML,如下所示,我需要显示每个节点的名称及其值。没有元素会有任何属性。
<?xml version="1.0" encoding="UTF-8"?>
<ResponseEnvelope xmlns="http://www.nwabcdfdfd.com/messagin" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseHeader>
<RequestId>directv_99e0857d-abf3-461c-913e-3ab59c6b5ef6</RequestId>
<ResponseId>1162969</ResponseId>
<MessageVersion>1.10</MessageVersion>
<RequestTimestamp>2013-02-12T17:26:28.172Z</RequestTimestamp>
<ResponseTimestamp>2013-02-12T17:26:50.409Z</ResponseTimestamp>
<SenderId>CarePortal2</SenderId>
<ProgramName />
<TestProdFlag>P</TestProdFlag>
<ResultCode>9</ResultCode>
<Locale>en_US</Locale>
<Errors>
<Error>
<ErrorCode>9</ErrorCode>
<ErrorNumber>90001</ErrorNumber>
<ErrorMessage>System error occurred</ErrorMessage>
<ErrorFieldId />
</Error>
</Errors>
</ResponseHeader>
<ResponseBody xsi:type="CPSingleSignOnResponse">
<PortalUserID>45497</PortalUserID>
<PartyID>1858186</PartyID>
<WarrantyItemName>DTV ABC WOLE HE P</WarrantyItemName>
<WarrantyInventoryItemId>138677</WarrantyInventoryItemId>
<ClientWarrantySku>202</ClientWarrantySku>
<ClientWarrantyDescription>DV Plan</ClientWarrantyDescription>
<ContractNumber>4003564</ContractNumber>
<IsPortalUserCreated>N</IsPortalUserCreated>
<IsPartyCreated>N</IsPartyCreated>
<IsContractUpdated>N</IsContractUpdated>
<IsFootPrintUpdated>N</IsFootPrintUpdated>
<Customer>
<PartyId>185812386</PartyId>
<Salutation />
<FirstName>Tejas</FirstName>
<LastName>Tanna</LastName>
<AddressList>
<Address>
<PartySiteId>3617490</PartySiteId>
<Type>BILTO</Type>
<Address1>CASCADES</Address1>
<Address2>202</Address2>
<Address3>RIDGE HEAVEN</Address3>
<Address4 />
<City>STERLING</City>
<State>VA</State>
<PostalCode>20165</PostalCode>
<County>LOUDOUN</County>
<Province />
<Country>US</Country>
<Urbanization />
<AddressStyle>US</AddressStyle>
</Address>
<Address>
<PartySiteId>3613791</PartySiteId>
<Type>SHIP_T</Type>
<Address1>CASADS</Address1>
<Address2>22</Address2>
<Address3>RIE HEEN</Address3>
<Address4 />
<City>STELI</City>
<State>VA</State>
<PostalCode>2065</PostalCode>
<County>LOUUN</County>
<Province />
<Country>US</Country>
<Urbanization />
<AddressStyle>US</AddressStyle>
</Address>
</AddressList>
<PhoneList>
<Phone>
<ContactPointId>2371717</ContactPointId>
<Type>HOME PNE</Type>
<PhoneNumber>51-62-7464</PhoneNumber>
<Country>1</Country>
<PrimaryFlag>Y</PrimaryFlag>
</Phone>
</PhoneList>
<EmailList>
<Email>
<ContactPointId>237516</ContactPointId>
<EmailAddress>a.abc@abc.com</EmailAddress>
<PrimaryFlag>Y</PrimaryFlag>
</Email>
</EmailList>
</Customer>
</ResponseBody>
</ResponseEnvelope>
这里唯一的挑战是可能有一些元素可能有自己的子元素,例如地址因此代码需要具有递归功能。
此外,不应显示没有任何文本的元素,如 Address4(只有子元素)。此外,不应显示省等元素。
我尝试了以下代码,但没有工作..
Sub Driver()
Range("4:" & Rows.Count).ClearContents
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
i = 4
xmlDoc.LoadXML (Range("A2"))
Set oParentNode = xmlDoc.DocumentElement.SelectNodes("ResponseBody")(0)
Call List_ChildNodes(oParentNode, i, "A", "B")
End Sub
Sub List_ChildNodes(oParentNode, i, NameColumn, ValueColumn)
For Each oChildNode In oParentNode.ChildNodes
If oChildNode.ChildNodes.Length > 1 Then
Call List_ChildNodes(oChildNode, i, NameColumn, ValueColumn)
Else
Cells(i, NameColumn) = oChildNode.tagname
Cells(i, ValueColumn) = oChildNode.Text
i = i + 1
End If
Next
End Sub
答案 0 :(得分:4)
假设您的XML位于单元格“A2”中,第一个问题是您的行
Set oParentNode = xmlDoc.DocumentElement.SelectNodes("ResponseBody")(0)
返回nothing
。将其更改为
Set oParentNode = xmlDoc.DocumentElement
并且代码至少要处理一些事情。
编辑1&amp; 2
另一个问题是节点内的节点不能提供正确的输出。要解决此问题,您需要稍微更改List_ChildNodes
功能。第一个修改适用于您提供的示例,但不适用于后一个修改,它不能使用我之前提供的代码正确解析。所以我添加了一个错误陷阱,确保即使是这个XML(正如我所相信的)也能正确读取。使用On Error Resume Next
的技巧本质上是VBA相当于Try ... Catch
语句(除了“catch”是:“如果出现错误则将L设置为零。我们实际上是先将L设置为零,并且不要在错误时覆盖它。同样的事情,不同的顺序。其中一个他们不在学校教的技巧!)
Sub List_ChildNodes(oParentNode, i, NameColumn, ValueColumn)
Dim L As Integer
For Each oChildNode In oParentNode.ChildNodes
L = 0
Err.Clear
On Error Resume Next
L = oChildNode.ChildNodes(0).ChildNodes.Length
If L > 0 Then
Call List_ChildNodes(oChildNode, i, NameColumn, ValueColumn)
Else
If Not oChildNode.Text = "" Then
Cells(i, NameColumn) = oChildNode.tagName
Cells(i, ValueColumn) = oChildNode.Text
i = i + 1
End If
End If
Next
End Sub
我已经使用您提供的更大的XML片段测试了最新版本,并且它似乎没有故障解析。我不打算逐行检查......
答案 1 :(得分:0)
Excel有一个内置的.xml导入程序。你不需要自己编写(除非你试图做一些不寻常的事情)。 http://office.microsoft.com/en-us/excel-help/import-xml-data-HP010206405.aspx#BMimport_an_xml_file_as_an_xml_list_wit
答案 2 :(得分:0)
试试这个版本。
注意:
以下是代码:
Option Explicit
Sub Driver()
Dim i As Long
Dim xmlDoc As Object
Dim oParentNode As Object
Dim bDiscard As Boolean
Range("4:" & Rows.Count).ClearContents
i = 4
Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
xmlDoc.Load "foo.xml"
xmlDoc.setProperty "SelectionNamespaces", "xmlns:r='http://www.nwabcdfdfd.com/messagin'"
Set oParentNode = xmlDoc.selectSingleNode("//r:ResponseBody")
bDiscard = listChildNodes(oParentNode, i, "A", "B")
End Sub
Function listChildNodes(oParentNode As Object, i As Long, NameColumn As String, ValueColumn As String) As Boolean
Dim oChildNode As Object
Dim bResult As Boolean
If (oParentNode.nodeType = 3) Then 'i.e. DOMNodeType.NODE_TEXT
Cells(i, ValueColumn).Value = oParentNode.Text
listChildNodes = True
Else
For Each oChildNode In oParentNode.childNodes
bResult = listChildNodes(oChildNode, i, NameColumn, ValueColumn)
If (bResult) Then
Cells(i, NameColumn).Value = oParentNode.nodeName
i = i + 1
End If
Next oChildNode
listChildNodes = False
End If
End Function