经典ASP循环通过XML

时间:2014-10-28 09:32:08

标签: xml asp-classic

我有一个XML有效负载如下

<tsResponse>
 <sites>
  <site id="site-id"  name="site1-name" contentUrl="site1-content-url"  /> 
   <projects>
    <project id="project1-id" name="project1-name"/>
    <project id="project2-id" name="project2-name"/>
   </projects>
  </site>
  <site id="site2-id" name="site2-name" contentUrl="site2-content-url" /> 
   <projects>
    <project id="project3-id" name="project3-name"/>
    <project id="project4-id" name="project4-name"/>
   </projects>
  </site>
 </sites>
</tsResponse>

我可以遍历每个站点,收集每个站点ID,名称和contentURL,因为我跟随以下内容

    Set oXML = Server.CreateObject("Microsoft.XMLDOM")
    oXML.LoadXML(postResponse) ' sXML is a variable containing the content of your XML file

    For Each oNode In oXML.SelectNodes("/tsResponse/sites/site")
        sID = oNode.GetAttribute("id")
        sName = oNode.GetAttribute("name")
        sContentURL = oNode.GetAttribute("contentUrl")
    Next
    Set oXML = Nothing

但是,如何在每个站点中获取每个项目ID和名称?我是否需要现有的另一个For循环或者效率太低?如何遍历特定属性= X的位置?

更新

For Each oNode In oXML.SelectNodes("/tsResponse/sites/site")
  sID = oNode.GetAttribute("id")
  sName = oNode.GetAttribute("name")
  sContentURL = oNode.GetAttribute("contentUrl")
  Response.write("<h2>"&sName&" / "&sID&" / "&sContentURL&"</h2>")
  For Each oNode In oXML.SelectNodes("/tsResponse/sites/site[@id='"&sID&"']/projects/project")
    pID = oNode.GetAttribute("id")
    pName = oNode.GetAttribute("name")
    Response.write("<h3>"&pID&" / "&pName&"</h3>")
  Next
Next
Set oXML = Nothing

在第二个For loop我得到Invalid 'for' loop control variable

将oNode更改为oNode2并且它可以正常工作!

1 个答案:

答案 0 :(得分:2)

For Each oNode In oXML.SelectNodes("/tsResponse/sites/site")
  sID = oNode.GetAttribute("id")
  sName = oNode.GetAttribute("name")
  sContentURL = oNode.GetAttribute("contentUrl")
  Response.write("<h2>"&sName&" / "&sID&" / "&sContentURL&"</h2>")
  For Each oNode2 In oXML.SelectNodes("/tsResponse/sites/site[@id='"&sID&"']/projects/project")
    pID = oNode2.GetAttribute("id")
    pName = oNode2.GetAttribute("name")
    Response.write("<h3>"&pID&" / "&pName&"</h3>")
  Next
Next
Set oXML = Nothing