使用vbs从XML删除节点

时间:2018-10-26 00:44:18

标签: xml vbscript

我在xml文件中有以下代码:

<?xml version="1.0" encoding="utf-8"?>
<settings id="2.0">
  <settings>
    <entry key="RecentFiles">
      <list>
        <value>\\proj01\1.jpg</value>
        <value>\\proj01\2.jpg</value>
        <value>\\proj01\3.jpg</value>
        <value>\\proj01\4.jpg</value>
        <value>\\proj01\5.jpg</value>
        <value>\\proj01\6.jpg</value>
        <value>\\proj01\7.jpg</value>
        <value>\\proj01\8.jpg</value>
        <value>\\proj01\9.jpg</value>
      </list>
    </entry>
    <child key="Options">
      <child key="DefaultFileDialogDirectories">
        <entry key="OpenAndSaveDirectory">C:\Users\XXXXX\Desktop</entry>
        <entry key="ImportDirectory">\\proj01\</entry>
        <entry key="BitmapDirectory">H:\Documents\Screengrabs</entry>
        <entry key="ExportDirectory">C:\Users\XXXXX\Desktop\_TempStuff</entry>
        <entry key="AttachReferenceFileDirectory">C:\Users\XXXXX\Desktop</entry>
        <entry key="WorksessionDirectory">C:\Users\XXXXX\Desktop</entry>
      </child>
    </child>
  </settings>
</settings>

并且我要删除“ RecentFiles”和“ DefaultFileDialogDirectories”

所以看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<settings id="2.0">
  <settings>
    <entry key="RecentFiles">
      <list>
      </list>
    </entry>
    <child key="Options">
      <child key="DefaultFileDialogDirectories">
      </child>
    </child>
  </settings>
</settings>

该怎么做?

在我失败的尝试下面:

Set objXMLDoc = Wscript.CreateObject("Microsoft.XMLDOM") 
objXMLDoc.async = False 

Dim XMLFile
XMLFile = "C:\Users\XXXXX\Desktop\settings.xml"
objXMLDoc.load(XMLFile) 

Set nodes = objXMLDoc.selectNodes("/settings/settings/entry key='RecentFiles'/list | " & _
                                  "/settings/settings/child key='Options'/child key='DefaultFileDialogDirectories'/")
For Each node In nodes
  node.parentNode.removeChild(node)
Next

objXMLDoc.Save(XMLFile)

我不能单独选择“ entry”和“ child”,因为还有许多其他节点使用与我在上面发布的代码中省略的相同标签。

请帮助!

1 个答案:

答案 0 :(得分:1)

这应该做

const cheerio = require('cheerio');
const $ = cheerio.load('<h1>hello</h1><p>sometext</p><img src="image.jpg"/><ul><li>one</li>two</li></ul>');

const h1 = $('h1');
const p = $('p');

我在XML负载和Option Explicit dim objXMLDoc Set objXMLDoc = Wscript.CreateObject("MSXML2.DomDocument") objXMLDoc.async = False Dim XMLFile XMLFile = "C:\Users\XXXXX\Desktop\settings.xml" if not objXMLDoc.load(XMLFile) then WScript.Echo "Error loading XML: " & objXMLDoc.parseError.reason WScript.Quit 1 end if dim nodes, node Set nodes = objXMLDoc.selectNodes("/settings/settings/entry[@key='RecentFiles']/list/value | " & _ "/settings/settings/child[@key='Options']/child[@key='DefaultFileDialogDirectories']/entry") For Each node In nodes node.parentNode.removeChild node Next objXMLDoc.Save XMLFile 上添加了错误检查,因为这总是很有帮助的。您的XPath仅需要更正属性选择器语法,即Option Explicit