微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有以下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>

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

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。