字符串到 XML 并在 ASP VBScript 中按 ID 访问特定值



我有一些xml字符串,我喜欢在asp VBscript中将其转换为XML对象。然后我喜欢根据父项的id属性访问子项:

…
<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>
…

例如,我想获取信息 id="dat2" new_val值。

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

这个代码片段给了我第一个new_val的值,但是我如何指定获取信息 id="dat2" 的值?

您可以使用 selectSingleNode 方法执行 xpath 查询。

像这样:

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

最新更新