Vipresh
Vipresh

Reputation: 89

String to XML and Access specific value by ID in ASP VBScript

I have some xml string which I like to convert to XML object in asp VBscript. Then I like to access the child item based on id attribute of the parent:

…
<subset>
<subtitle>DEMAND</subtitle>
<information id="dat1" timestamp="2017-01-26T10:00:00.000-05:00">
    <info_title>Market Demand</info_title>
    <new_val>19887.4</new_val>
    <old_val>19584.3</old_val>
</information>
<information id="dat2" timestamp="2017-01-26T10:45:00.000-05:00">
    <info_title>5-Minute Market Demand</info_title>
    <new_val>19742.2</new_val>
    <old_val>19712.7</old_val>
</information>
<information id="dat3" timestamp="2017-01-26T10:00:00.000-05:00">
    <info_title>Ontario Demand</info_title>
    <new_val>17204.7</new_val>
    <old_val>17076.4</old_val>
</information>
</subset>
…

For example, I want to get the information id=”dat2” new_val value.

function getXMLValue(strXMLfile, XMLelement, infoID, XMLattrib)

    'Declare local variables
    Dim objXML, return_value
    return_value = null

    'Instantiate the XMLDOM Object that will hold the XML file.
    set objXML = Server.CreateObject("Microsoft.XMLDOM")

    'Turn off asyncronous file loading.
    objXML.async = false

    objXML.LoadXml(strXMLFile)
    objXML.setProperty "SelectionLanguage", "XPath" 

    if XMLelement = "date" then
        set return_value = objXML.selectSingleNode("date/@" & XMLattrib)

    elseif XMLelement = "id" then
        set return_value = objXML.selectSingleNode("subset/information[@id='" & infoID & "']/" & XMLattrib)

    elseif XMLelement = "page_title" then
        set return_value = objXML.selectSingleNode("page_title")

    elseif XMLelement = "date_stamp" then
        set return_value = objXML.selectSingleNode("date" & XMLvalue)

    elseif XMLelement = "timestamp" then
        set return_value = objXML.selectSingleNode("subset/information/[@id='" & infoID & "']/timestamp/@" & XMLattrib)

    end if  

    if not(isnull(return_value)) then
        getXMLvalue = return_value.text
    end if

    set return_value = nothing
    set objXML = nothing
end function

This code snippet gives me the value of the first new_val, but how do I specify to get the value of information id=”dat2”?

Upvotes: 0

Views: 146

Answers (1)

Kevin Collins
Kevin Collins

Reputation: 1461

You can execute an xpath query with selectSingleNode method.

Something like this:

objXML.setProperty "SelectionLanguage", "XPath"
set objNode = objXML.selectSingleNode("/subset/information[@id='dat2']/new_val")
if not objNode is nothing then
    MsgBox objNode.text
end if

Upvotes: 2

Related Questions