VBS从目录中的所有xml文档中提取节点

时间:2014-07-07 09:28:14

标签: xml vbscript

我有下面的VBS,它从一个xml中提取出两个属性,我想修改代码以查看数据目录并为其中的所有xml文档提取这两个属性。

如果可以将每个文件的输出放在同一行上,也会很整洁。

用户名 - ID而不是当前的

用户名

ID

 Set objXML2 = CreateObject("Microsoft.XMLDOM")
    objXML2.async = "false"
    strdir="c:\temp\XML\Data\test.xml"
    If (Not objXML2.load(strdir)) Then
        wscript.echo "Unable to load file '" & strdir & "'. "
        WScript.Quit(1)
    End If
    Set colNodes1 = objXML2.selectNodes ("/User/Username") 
    For Each objNode in colNodes1
        wscript.echo objnode.getAttribute("name") & objNode.text 
    NEXT
    Set colNodes2 = objXML2.selectNodes ("/User/ID") 
    For Each objNode in colNodes2 
        wscript.echo objnode.getAttribute("name") & objNode.text

    NEXT 

xml的小例子,将是不同的标签,但格式将是相同的。

<Batch>
 <User>
  <Username>Ignatius</Username>
  <Department>IT</Department>
  <ID>123456</ID>
 </User>
</Batch>

我怎样才能从下面的XML中取出Town?在同一行?并将其放入文本文件中?

<Batch>
<User>
 <Detail> 
   <Username>Ignatius</Username>
   <Department>IT</Department>
   <ID>123456</ID>
 </Detail>
 <Location>
   <Town>London</Town>
 </Location>
</User>
</Batch>

1 个答案:

答案 0 :(得分:0)

关键概念:

  1. 循环文件夹的文件
  2. 过滤特定文件
  3. .selectNodes以获取所需节点列表
  4. .selectSingleNode for single nodes(surprise!)
  5. 如此处使用:

      Dim oFS    : Set oFS    = CreateObject("Scripting.FileSystemObject")
      Dim objXML : Set objXML = CreateObject("MSXML2.DOMDocument")
      objXML.async = false
      Dim oFile
      For Each oFile In oFS.GetFolder("..\data").Files
          WScript.Echo oFile.Path
          If 1 = InStr(oFile.Name, "24607266") Then
              objXML.load oFile.Path
              If objXML.parseError Then ' never without my check
                 WScript.Echo objXML.parseError.reason
              Else
                 Dim sXPath : sXPath = "/Batch/User"
                 Dim ndlUsers : Set ndlUsers = objXML.selectNodes(sXPath)
                 If 0 = ndlUsers.length Then ' never without my check
                    WScript.Echo "fail:", sXPath
                 Else
                    Dim ndUser
                    For Each ndUser In ndlUsers
                        ' no attribs!
                        ' WScript.Echo ndUser.getAttribute("Name"), ndUser.getAttribute("Id")
                        WScript.Echo ndUser.selectSingleNode("Username").text, ndUser.selectSingleNode("ID").text
                    Next
                 End If
              End If
          End If
      Next
    

    (开始研究here。)