如何使用tcl更改XML标记的值

时间:2015-09-11 21:12:17

标签: xml tcl

我有一个XML文件如下: -

<ii:variable name="SERVER_IP" type="string" value="10.39.1.105:5005" />
<ii:variable name="DEVICE_WAN" type="string" value="em1" />
<ii:variable name="DEVICE_LAN" type="string" value="eth1" />
<ii:variable name="NUT_WAN_MAC" type="macaddress" value="00:10:18:DE:66:43" />
<ii:variable name="NUT_LAN_MAC" type="macaddress" value="00:10:18:DE:66:45" />

<ii:variable name="NUT_WAN_ID" type="ipv6interfaceid" value="0210:18FF:FEDE:6643" />

<ii:variable name="NUT_LAN_ID" type="ipv6interfaceid" value="0210:18FF:FEDE:6645" />

<ii:variable name="NUT_LAN_GLOBAL_ID" type="ipv6interfaceid" value="0210:18FF:FEDE:6645" />

<ii:variable name="NUT_LAN_ULA_PREFIX" type="ipv6address" value="FD00::" />

<ii:variable name="CONFIG_DIR" type="string" value="/cygdrive/c/Intact/33843evg/" />

<ii:variable name="DAD_TIME" type="integer" value="240000" />
<ii:variable name="DHCP_SOL_WAIT" type="integer" value="10000" />
<ii:variable name="DHCP_LAN_SOL" type="integer" value="5000" />

现在,我想要改变&#34;值&#34;某个变量的字段&#34; name&#34;字段,如ii:变量名=&#34; NUT_WAN_MAC,ii:变量名=&#34; NUT_LAN_MAC等。 使用TCL脚本的最佳方法是什么。

1 个答案:

答案 0 :(得分:0)

tdom包很擅长这种事情:

package require tdom

# Parse the XML into a DOM tree
set doc [dom parse $thexml]

# Note that we've got a (multi-line) list of the changes to make
# and that I have *NO* idea what you want to set things to!
foreach {name setTo} {
    NUT_WAN_MAC "the quick brown fox"
    NUT_LAN_MAC "the lazy dogs"
} {
    # using a loop in case there are several nodes with that name :-)
    foreach node [$doc selectNodes [format {//ii:variable[@name="%s"]} $name]] {
        $node setAttribute value $setTo
    }
}

# Convert back into XML; you might want to experiment with the -indent option
set thechangedxml [$doc asXML]

您可能需要尝试在XP selectNodes方法中使用XPath来选择要修改的节点;这些东西并不总是微不足道的。如果您正在使用包含[过滤器]的XPath,请记住支持整体表达式以防止双重解释,format命令可以帮助您保持理智。

是的,如果你愿意,你可以把它变得更复杂。 (我省略了读取和写入文件的代码。这非常标准。)