2017-02-10 17 views
0

我有一些xml字符串,我喜欢在asp VBscript中转换为XML对象。 后来我想基于父的id属性来访问子项:字符串到XML和访问特定值在ASP VBScript中的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” 的价值?

回答

2

您可以使用selectSingleNode method执行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 
+0

HI凯文,似乎并没有工作。我上面更新了我的代码。注意:strXMLfile是我上面提供的XML字符串。 – Vipresh

+0

请在您调用getXMLValue函数的地方发布代码。另外,这里的xml是从开始的strXMLfile的全部,还是有更多? –

+0

调用getXMLValue的实例:getXMLvalue(strXMLfile,“id”,“dat2”,“new_val”)。还有更多的strXMLfile xml ....此外,如果我更改strXMLfile指向本地xml文件,它的工作原理,但我想通过它作为一个字符串.. – Vipresh