【问题标题】:how to change the value of a XML tag using tcl如何使用 tcl 更改 XML 标记的值
【发布时间】:2015-09-15 22:45:08
【问题描述】:

我有一个如下的 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" />

现在,我想更改某些变量“名称”字段的“值”字段,例如 ii:variable name="NUT_WAN_MAC, ii:variable name="NUT_LAN_MAC,etc 等。 使用 TCL 脚本的最佳方法是什么。

【问题讨论】:

标签: xml tcl


【解决方案1】:

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]

您可能需要尝试让 XPath 在 selectNodes 方法中使用正确的东西来选择要修改的节点;这些事情并不总是微不足道的。如果您正在使用包括 [filters] 在内的 XPath,请记住支撑整个表达式以防止双重解释,format 命令可以帮助您保持清醒。

是的,如果你愿意,你可以让这变得更复杂。 (我省略了读写文件的代码。这很标准。)

【讨论】:

  • 感谢您的建议 Donal,我尝试了代码,但它不起作用。实际上让我把我正在谈论的整个文件。文件名是“devices.xml”,内容是:-
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多