使用VBScript读取多个XML

时间:2013-12-03 19:02:06

标签: xml xpath vbscript

我在VBScript中有以下代码:

Dim OrganizationInfo, name
Dim Location, country

Set xmlDoc = CreateObject("Microsoft.XMLDOM") 
xmlDoc.Async = "False"
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("C:\Users\AdminUser\XMLArchive.xml")

Set fso = CreateObject("Scripting.FileSystemObject")
Const ForAppending = 8
Set WriterObject = fso.OpenTextFile("C:\Users\AdminUser\Folder\TEXTFile.txt", ForAppending, True) 


For Each OrganizationInfo In xmlDoc.SelectNodes("//OrganizationInfo/OrganizationName")
    name = OrganizationInfo.Text

    For Each Location In OrganizationInfo.SelectNodes("//Location")
        COUNTRY = Location.Text
        WriterObject.WriteLine DATA & ";" & Pais
    Next
Next

我正在使用Xpath在多个txts中编写大量XML Node的文本,没有任何问题。

现在我需要在插入“XMLArchive.xml”的同一目录中使用1000个XML重复此过程,而不知道他们的名字......任何人都可以帮忙吗? 我在这里看过类似的案例,但没有一个具有相同的意图。

2 个答案:

答案 0 :(得分:0)

如有疑问,请阅读documentation。目录中的文件可以像这样处理:

Set fso = CreateObject("Scripting.FileSystemObject")

Set xml = CreateObject("Msxml2.DOMDocument.6.0") 
xml.Async = False
xml.setProperty "SelectionLanguage", "XPath"

For Each f In fso.GetFolder("C:\Users\AdminUser").Files
  If LCase(fso.GetExtensionName(f)) = "xml" Then
    xml.Load f.Path

    If xml.ParseError = 0 Then
      'your XML processing code goes here
    Else
      WScript.Echo "Error parsing '" & f.Path & "': " & xml.ParseError.Reason
    End If
  End If
Next

答案 1 :(得分:0)

这是一个Sub,它可以找到您指定的文件夹中所有XML文件的名称。

有关将完整的 VBScript参考下载为Windows帮助文件的说明,请参阅this answer

Sub ProcessXmlFiles(sFolderPath)
    Dim oFso, oFolder
    Dim sFilePath

    Set oFso = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFso.GetFolder(sFolderPath)
    For Each sFilePath In oFolder.Files
        If IsXmlFile(sFilePath) Then
            WScript.Echo sFilePath
            ' ProcessXmlFile(sFilePath)  ' Do your XML file processing here!
        End If
    Next

    Set oFolder = Nothing
    Set oFso = Nothing
End Sub

Function IsXmlFile(sFilePath)
    Const REGEXPR = "\.xml$"
    Dim oRegex, oMatches

    Set oRegex = New RegExp
    oRegex.Pattern = REGEXPR
    oRegex.IgnoreCase = True
    oRegex.Global = False
    Set oMatches = oRegex.Execute(sFilePath)

    IsXmlFile = (oMatches.Count > 0)
    Set oMatches = Nothing
    Set oRegex = Nothing
End Function