使用经典的asp和xpath解析XML

时间:2014-07-01 19:35:36

标签: xml xpath vbscript asp-classic

我正在尝试使用经典的asp在我的XML中读取我的“保存”节点,它给了我一个错误,我知道某处有一个小问题,我似乎无法弄清楚......任何想法? 这是所需的错误对象:'order.item(...)'

<%
    Dim email,template,featured, monthx 

    email = "email@example.com"
    monthx = "week1"
    featured = "featured"

    set objXML = Server.CreateObject("MSXML2.DOMDocument")
    objXML.async = false    
    objXML.load(Server.MapPath("records.xml"))

    'Find if order exists
    xPath = "//rep[@email='"&email&"']/month[@name='" & monthx & "']/product[@type='" & featured & "']/saving"
    set order = objXML.selectNodes(xPath)   


        retStr = retStr & order.item(i).selectSingleNode("saving").text & ","

        Response.Write(retStr)


    set objXML = nothing    
%>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<replist>
  <rep email="email@example.com">
    <month name="Week1">
      <product type="featured">
        <model>Honda</model>
        <i>G</i>
        <p>7</p>
        <e>AA</e>
        <sn>123432</sn>
        <saving>save 30</saving>
      </product>
    </month>
  </rep>
</replist>

1 个答案:

答案 0 :(得分:0)

阅读本文并修正错误(下次发布的数字,行,描述):

email = "email@example.com" ' not example@example.com
monthX = "Week1"  ' can't use name of Month function as variable name
featured = "featured"

set objXML = CreateObject("MSXML2.DOMDocument")
objXML.async = false
objXML.load "24517985.xml"

If objXML.parseError Then ' never without my check
   WScript.Echo objXML.parseError.reason
Else
   'Find list of all ...saving nodes
   xPath = "//rep[@email='"&email&"']/month[@name='" & monthX & "']/product[@type='" & featured & "']/saving"
   set order = objXML.selectNodes(xPath)
   If 0 = order.length Then ' never without my check
      WScript.Echo "fail:", xPath
   Else
'     WScript.Echo order.item(i).selectSingleNode("saving").text & ","
'     we got a ...saving, no need for this rigmarole
      WScript.Echo order(0).tagName, order(0).text
   End If
End If

输出:

cscript 24517985.vbs
saving save 30

更新wrt编辑问题:

错误:“需要对象:'order.item(...)'”是由

引起的
  • by selectSingleNode()返回一个空的/ 0长度节点集合,因为
  • XPath查询失败,因为我的评论中提到了各种错误
  • 未检查失败