for循环的每个循环的vbscript

时间:2016-03-17 07:07:39

标签: xml xpath vbscript

您好我已经在VBScript中编写了一个程序,现在我想用For Each循环替换For循环。

For Each node In objMSXML.selectNodes(sXPath)                   
    Set li = document.createElement("li")
    li.innerText = i & " " & node.text
    ul.appendChild li
    i = i +1
Next

我无法弄明白,因为我还需要知道从Xpath返回的节点数。

2 个答案:

答案 0 :(得分:3)

继续我的initial comment

selectNodes()方法返回IXMLDOMNodeList对象,该对象是NodeList集合。

与任何集合一样,它包含集合对象的通用成员

  

<强>属性

     
      
  • length - 集合中的节点数
  •   
     

<强>方法

     
      
  • item - 访问集合中的各个节点
  •   
     

有关成员属性和方法的完整列表,请参阅   IXMLDOMNodeList Members

由于您只需使用For Each属性来检索集合中的节点数,因此您无需将For更改为length循环的逻辑原因。

Option Explicit

Dim node, nodes, li, i, sXPath, NumberOfNodes
Set nodes = objMSXML.selectNodes(sXPath)
'Retrieve number of Nodes
NumberOfNodes = nodes.length
For Each node In nodes                   
    Set li = document.createElement("li")
    li.innerText = i & " " & node.text
    ul.appendChild li
    i = i +1
Next

有用的链接

答案 1 :(得分:2)

.SelectNodes()返回的节点列表是一个具有.length属性的集合,可以使用从零开始的整数索引遍历:

Option Explicit

Dim oFS    : Set oFS  = CreateObject("Scripting.FileSystemObject")
Dim sFSpec : sFSpec   = oFS.GetAbsolutePathName("..\data\33921005.xml")
Dim oXML   : Set oXML = CreateObject("Msxml2.DOMDocument.6.0")
oXML.load sFSpec
If 0 = oXML.parseError Then
   Dim ndlName : Set ndlName = oXML.selectNodes("/Envelope/Body/Request/individual/hasName/*")
   Dim ndName
   For Each ndName In ndlName
       WScript.Echo ndName.tagName
   Next
   Dim iNd
   For iNd = 0 To ndlName.length - 1
       WScript.Echo iNd, ndlName(iNd).tagName
   Next
Else
   WScript.Echo oXML.parseError.reason
End If

输出:

cscript 36053711.vbs
firstName
lastName
0 firstName
1 lastName
相关问题