MS Access VB XML解析问题

时间:2016-02-22 15:11:24

标签: xml vba ms-access-2010

我正在尝试在MS Access中创建一个表单,允许用户向USPS发送地址进行验证并获取正确的地址。我有大部分工作,但对XML和解析我是新手我在其他地方找到的代码,并试图让它工作。我已经能够发送数据并使用XML接收响应。但是我无法弄清楚如何解析节点。示例我将有一个表单,其中一个人放置地址1,2,城市,州,邮政等...我希望结果返回到那些表单字段或至少在字段旁边的文本框中。我可以作为测试显示从USPS返回的结果,但它显然包含XML代码。所以现在我必须解析XML中的数据并显示它。但我无法得到我正在寻找的数据。举个例子,假设我想从代码中获取地址1,城市,zip5。就发送数据和接收固定地址而言,这就是我的工作。但同样,我似乎无法获取数据。

我怀疑根据以前的错误设置cstrXpath是不正确的。现在这个代码确实显示了msgbox的完整结果,包括代码AT MsgBox myDom.XML,但不显示应该只显示地址和zip5的消息。

Private Sub Command0_Click()


Const cstrXPath As String = "/Address:Address1/Address2/City/State/Zip5/Zip4"

Dim myDom As MSXML2.DOMDocument
Dim xmlElement As MSXML2.IXMLDOMElement
Dim xmlSelection As MSXML2.IXMLDOMSelection
Dim i As Long
Dim myXML As String

 myXML = "http://production.shippingapis.com/ShippingAPITest.dll?API=Verify&XML=" & _
    "<AddressValidateRequest%20USERID=" & Chr(34) & "XXXXXXACCOUNTXX" & Chr(34) & "><Address>" & _
    "<Address1></Address1>" & _
    "<Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State>" & _
    "<Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>"

'Set myDom = CreateObject("MSXML2.DOMDocument")
Set myDom = New MSXML2.DOMDocument
myDom.async = False
myDom.Load (myXML)

Set xmlSelection = myDom.selectNodes(cstrXPath)
'Debug.Print "xmlSelection.Length: " & xmlSelection.length
'i = 1
For Each xmlElement In xmlSelection
    MsgBox xmlElement.getAttribute("Address1") & xmlElement.getAttribute("Zip5")
 '   i = i + 1
Next xmlElement

    MsgBox myDom.XML
End Sub

1 个答案:

答案 0 :(得分:1)

这可能相当简单,但它似乎完成了工作:

Option Compare Database
Option Explicit

Sub xmlParseTest()
    Dim myDom As New MSXML2.DOMDocument
    myDom.SetProperty "SelectionLanguage", "XPath"
    ' test data
    myDom.LoadXML _
            "<?xml version=""1.0""?>" & _
            "<AddressValidateResponse>" & _
                "<Address>" & _
                    "<Address2>6406 IVY LN</Address2>" & _
                    "<City>GREENBELT</City>" & _
                    "<State>MD</State>" & _
                    "<Zip5>20770</Zip5>" & _
                    "<Zip4>1441??</Zip4>" & _
                "</Address>" & _
            "</AddressValidateResponse>" & _
            ""
    Dim addr As MSXML2.IXMLDOMElement
    For Each addr In myDom.SelectNodes("//Address")
        Debug.Print "Start of Address"
        Dim item As MSXML2.IXMLDOMElement
        For Each item In addr.ChildNodes
            Debug.Print "    " & item.BaseName & ": " & item.Text
        Next
        Set item = Nothing
        Debug.Print "End of Address"
    Next
    Set addr = Nothing
    Set myDom = Nothing
End Sub

在VBA立即窗口中生成以下输出:

Start of Address
    Address2: 6406 IVY LN
    City: GREENBELT
    State: MD
    Zip5: 20770
    Zip4: 1441??
End of Address