使用VBScript将XMLstring直接写入XML文件

我的操作系统是Windows 7 64位。 我需要通过使用VBScript将下面的XMLstring和解释的dynamic内容一起写入XML文件(也维护制表符缩进):

文件名: [Variable1]_[Variable2].xml

 <?xml version="1.0"?> <config> <modules> <[Variable1]_[Variable2]> <active>true</active> <codePool>[Variable3]</codePool> <version>[Variable4]</version> </[Variable1]_[Variable2]> </modules> </config> 

我所能做的就是在脚本下面一个接一个地创build各种标签和元素。

 scriptDir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) Set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0") Set objRoot = xmlDoc.CreateElement("config") xmlDoc.AppendChild objRoot Set objRecord = xmlDoc.CreateElement("modules") objRoot.AppendChild objRecord Set objName = xmlDoc.CreateElement("Mageweb_ShippingFilter") objName.Text = "" objRecord.AppendChild objName Set objDate = xmlDoc.CreateElement("AuditDate") objDate.Text = Date objRecord.AppendChild objDate Set objIntro = xmlDoc.CreateProcessingInstruction("xml", "version='1.0'") xmlDoc.InsertBefore objIntro, xmlDoc.ChildNodes(0) 'For now there is static name of file xmlDoc.Save scriptDir & "\Testfile.xml" 

但是,这对于未来可能的大型XML文件来说似乎太麻烦了,所以我可以直接写XML文件,然后给出一个基于variables的dynamic名称用VBScript?

一般来说,XML数据应该使用XML工具(DOM操作,XSLT)进行处理,这正是因为当问题的规模/复杂度增长时,这些方法往往会更好地扩展。

但是对于使用RegExp替换函数和字典的特殊情况(例如ASCII编码,替换的简单标记)可以有效地解决模板化任务(请参见此处 )。

演示代码:

 Option Explicit Function fnRepl(sM, nP, sS) fnRepl = gdX(sM) End Function Function mkDic(aK, aV) Dim tmp : Set tmp = CreateObject("Scripting.Dictionary") Dim i For i = 0 To UBound(aK) tmp(aK(i)) = aV(i) Next Set mkDic = tmp End Function Dim gdX : Set gdX = mkDic( _ Split("[Variable1] [Variable2] [Variable3] [Variable4]") _ , Split("abra cada bra sesame") _ ) Dim r : Set r = New RegExp r.Global = True r.Pattern = "\[[^\]]+\]" Dim sT : sT = Join(Array( _ "<?xml version=""1.0""?>" _ , "<config>" _ , " <modules>" _ , " <[Variable1]_[Variable2]>" _ , " <active>true</active>" _ , " <codePool>[Variable3]</codePool>" _ , " <version>[Variable4]</version>" _ , " </[Variable1]_[Variable2]>" _ , " </modules>" _ , "</config>" _ ), vbCrLf) WScript.Echo sT WScript.Echo "----------" WScript.Echo r.Replace(sT, GetRef("fnRepl")) 

输出:

 cscript 45553911.vbs <?xml version="1.0"?> <config> <modules> <[Variable1]_[Variable2]> <active>true</active> <codePool>[Variable3]</codePool> <version>[Variable4]</version> </[Variable1]_[Variable2]> </modules> </config> ---------- <?xml version="1.0"?> <config> <modules> <abra_cada> <active>true</active> <codePool>bra</codePool> <version>sesame</version> </abra_cada> </modules> </config> 

看看这是否有帮助

 Set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0") xmlDoc.LoadXML strXML 'strXML being your xml string xmlDoc.Save strPath 'Directory and name of the save location 

为了使这个方法起作用,strXML变量应该事先解释变量。 你可以使用字符串方法来实现。

PS我已经写了这个片段在手机上,可能会有一些错误,但这应该有前路。