VBScript改变顶级节点

时间:2014-06-05 13:07:13

标签: xml vbscript rename xmlnode

我有一个自动导出的xml文件,但是带有错误的节点/元素。导出时看起来如下:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<StraightTableBox>
 <order>
  <ordernr>10000</ordernr>
  <trackingcode>JVGL0123456789101112</trackingcode>
  <trackingurl>http://www.dhl-tracknet.nl/cgi-bin-al/UFA100/NL/?type=U&amp;#38;zoekveld=JVGL0123456789101112</trackingurl>
 </order>
 <order>
  <ordernr>20000</ordernr>
  <trackingcode>JVGL0123456789101113</trackingcode>
  <trackingurl>http://www.dhl-tracknet.nl/cgi-bin-al/UFA100/NL/?type=U&amp;#38;zoekveld=JVGL0123456789101113</trackingurl>
 </order>
 <order>
  <ordernr>30000</ordernr>
  <trackingcode>JVGL0123456789101114</trackingcode>
  <trackingurl>http://www.dhl-tracknet.nl/cgi-bin-al/UFA100/NL/?type=U&amp;#38;zoekveld=JVGL0123456789101114</trackingurl>
 </order>
 <order>
  <ordernr>40000</ordernr>
  <trackingcode>JVGL0123456789101115</trackingcode>
  <trackingurl>http://www.dhl-tracknet.nl/cgi-bin-al/UFA100/NL/?type=U&amp;#38;zoekveld=JVGL0123456789101115</trackingurl>
 </order>
</StraightTableBox>

现在我需要更改和通过VBScript。

到目前为止,我设法打开文档,选择它所关注的节点(至少我认为)并保存已编辑的文档。但是更改节点的名称并不起作用。

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.load "H:\Scripts\Tracktrace.xml"

'Locate the desired node
'Note the use of XPATH instead of looping over all the child nodes
Set nNode = xmlDoc.selectsinglenode ("StraightTableBox")

'Save the xml document with the new node.
strResult = xmldoc.save("TracktraceEdited.xml")

如何将节点更改为我需要的节点?

1 个答案:

答案 0 :(得分:0)

由于您无法更改.tagName,并且字符串操作可能会导致问题(utf-8编码)以后,您需要创建一个新元素“orders”,附加原始documentElement的子元素和'replace'与新节点。在代码中(基于this):

  Dim oFS      : Set oFS      = CreateObject("Scripting.FileSystemObject")
  Dim sFSpec   : sFSpec       = oFS.GetAbsolutePathName("..\testdata\xml\order-1.xml")
  Dim objMSXML : Set objMSXML = CreateObject("Msxml2.DOMDocument")
  objMSXML.async = False
  objMSXML.load sFSpec

  If 0 = objMSXML.parseError Then
     Dim ndDE : Set ndDE = objMSXML.createElement("orders")
     Dim ndO
     For Each ndO In objMSXML.documentElement.childNodes
         ndDE.appendChild ndO
     Next
     Set objMSXML.documentElement = ndDE
     WScript.Echo objMSXML.xml
     objMSXML.save Replace(sFSpec, "-1", "-2")
  Else
     WScript.Echo objMSXML.parseError.reason
  End If

更新评论:

我通常以:

开始我的脚本
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

当我试图让我的测试脚本“独立”时,我搞砸了这些名字。抱歉。所以使用:

Dim sFSpec   : sFSpec       = oFS.GetAbsolutePathName("..\testdata\xml\order-1.xml")