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