我如何解析tcl脚本中的xml文件并读取一些标记属性并更改该属性值

Piy*_*ush 3 xml tcl

我有以下xml文件suing tcl脚本语言.

<workarea>
  <poller name="Poller1">
    <pollerAttribute loc="c:\abc" username="abc" password="xxx">
      <value>123</value>
    </pollerAttribute>
  </poller>
  <poller name="Poller2">
    <pollerAttribute loc="c:\def" username="def" password="xxx">
      <value>345</value>
    </pollerAttribute>
  </poller>
  .....
</workarea>
Run Code Online (Sandbox Code Playgroud)

在这里,我想用Poller名称读取每个tage,然后更改password="xxx"为此.我是tcl脚本语言的新手.任何帮助对我来说都很棒.谢谢你.

Don*_*ows 7

到目前为止,使用Tcl执行此操作的最简单方法是使用tDOM来操作XML.您使用XPath表达式来选择password要更改其属性的元素,然后您可以迭代这些节点并根据需要进行更改.最后,您需要记住,更改内存中的文档不会更改磁盘上的文档; 读取和编写序列化文档也是重要的步骤.

package require tdom

set filename "thefile.xml"
set xpath {//pollerAttribute[@password]}

# Read in
set f [open $filename]
set doc [dom parse [read $f]]
close $f
set root [$doc documentElement]

# Do the update of the in-memory doc
foreach pollerAttr [$root selectNodes $xpath] {
    $pollerAttr setAttribute password "theNewPassword"
}

# Write out (you might or might not want the -doctypeDeclaration option)
set f [open $filename "w"]
$doc asXML -channel $f -doctypeDeclaration true
close $f
Run Code Online (Sandbox Code Playgroud)

就是这样.(您可能需要更加谨慎地选择具有正确password属性的元素,并以更复杂的方式提供替换密码,但这些都是狡猾的.)