Search code examples
xmlvbscripttraversal

Issue with traversing through XML data - the VBScript way


Sample XML:

<cart subTotal="USD 3.50" >

    <item productSubTotal="3.50" >
        <pkProductItem>241</pkProductItem>
        <itemCode>23455-green-XL</itemCode>
        <itemName>my product ( green - XL-size )</itemName>
        <qty>1</qty>
        <itemUnitPrice>3.50</itemUnitPrice>
        <totalItemPrice>3.50</totalItemPrice>
    </item>

    <item productSubTotal="9.90" >
        <pkProductItem>123</pkProductItem>
        <itemCode>23455-green-XL</itemCode>
        <itemName>my product ( red - L-size )</itemName>
        <qty>1</qty>
        <itemUnitPrice>9.90</itemUnitPrice>
        <totalItemPrice>9.90</totalItemPrice>
        <options> </options>
    </item>

</cart>

<finalTotalValue>3.50</finalTotalValue>

Dim myXML: myXML= <the full xml string above>

Note: The XML data above IS generated by using string concatenation. The above XML data IS NOT loaded from an XML file.

After generated, how to use ASP VBScript to traverse through to read the data back?

  1. How to retrieve <finalTotalValue> ?

    Dim oXML, URI
    Set oXML = Server.CreateObject("MSXML2.DomDocument")
    oXML.loadXML(objXMLhttp.responseText)
    URI = oXML.selectSingleNode("//itemCode").text
    

This seems not to be working.

  1. How to retrieve item(s) inside cart using for loop? Inside <cart> can have multiple items.

  2. How to retrieve value inside the tag? E.g.: <item productSubTotal="9.90" > I want to get 9.90, by looping through products inside the cart XML.

I appreciate any help.


Solution

  • This tutorial should help.

    To loop through the cart you can do something like this:

    totalcost = 0
    set Cart_node = oXML.getElementsByTagName("cart")
    ' Loop through the cart node
    for each itemNodes in Cart_node(0).ChildNodes
        ' get the product sub total from each item node
        productSubTotal = itemNodes.getAttribute("productSubTotal")
        ' Loop through each item node
        for each item in itemNodes.ChildNodes
            ' if the node name is "totalItemPrice" add the value to the totalcost
            if item.nodeName = "totalItemPrice" Then
                totalcost = totalcost + item.Text
            end if
        Next
    Next
    ' totalcost will be the total of all values in totalItemPrice nodes.
    

    You can retrieve finalTotalValue like this:

    set final = oXML.getElementsByTagName("finalTotalValue")
    finalTotalValue = final(0).text