循环遍历所有XML元素并根据文本文件的输入附加XML文件

时间:2017-03-06 10:43:29

标签: xml vbscript

我想遍历XML文件中的所有元素,并通过文本文件将值分配给元素。

project_template.xml

<project baseDir="" outputDir="">
  <rule inherit="" preset="" pattern=""  /> 
</project> 

test.txt

baseDir="test1"
outputDir="test2"
inherit="test3"
preset="test4"
pattern="true"

Project.vbs

Option Explicit 
Dim arrFileLines(), final(45)
Dim i, objFSO, objFile, l, index, finalString
i = 0

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\1021752\Desktop\project\test.txt", 1)
Do Until objFile.AtEndOfStream
  ReDim Preserve arrFileLines(i)
  arrFileLines(i) = objFile.ReadLine
  i = i + 1
Loop
objFile.Close

Const NODE_ELEMENT = 1
Const CONFUSER_NS = "http://confuser.codeplex.com"

Dim doc, moduleElem, args, arg

Set args = WScript.Arguments
Set doc = CreateObject("Msxml2.DOMDocument")

doc.Async = False
doc.Load "project_template.xml"

If doc.ParseError.ErrorCode Then
  WScript.Echo doc.ParseError
  WScript.Quit 1
End If

For l = LBound(arrFileLines) To UBound(arrFileLines) Step 1
  index = InStr(1, arrFileLines(l), "=")
  final(l) = Right(arrFileLines(l), Len(arrFileLines(l)) - index)
Next
doc.DocumentElement.SetAttribute "baseDir", final(0)    'here I am manually assigning the value to the "baseDir"
doc.DocumentElement.SetAttribute "outputDir", final(1) 
doc.DocumentElement.SetAttribute "inherit", final(2)
doc.DocumentElement.SetAttribute "preset", final(3)
doc.DocumentElement.SetAttribute "pattern", final(4)
doc.Save "project.xml"

期望的输出:

<project baseDir="test1" outputDir="test2" >
  <rule inherit="test3" preset="test4" pattern="true"  />
</project> 

我希望代码遍历XML文件中的所有元素并返回名称。

1 个答案:

答案 0 :(得分:0)

我建议您将参数文件读入dictionary

Set fso = CreateObject("Scripting.FileSystemObject")

Set d = CreateObject("Scripting.Dictionary")
Set f = fso.OpenTextFile("C:\Users\1021752\Desktop\project\test.txt")
Do Until f.AtEndOfStream
  arr = Split(f.ReadLine, "=", 2)
  d(arr(0)) = Replace(arr(1), """", "")
Loop
f.Close

此外,您的代码会将所有属性添加到XML数据的根节点,而不是更新每个单独节点的属性。您需要的是一个递归过程,它更新当前节点中存在的属性,然后对其所有子节点执行相同的操作:

Sub UpdateAttributes(node, values)
  For Each attr In node.Attributes
    If values.Exists(attr.Name) Then node.SetAttribute attr.Name, values(attr.Name)
  Next

  For Each child In node.ChildNodes
    UpdateAttributes child, values
  Next
End Sub

使用XML根节点和字典调用该过程:

UpdateAttributes doc.DocumentElement, d