我正在编写一个PythonXML(NETCONF)解析器,目标是从服务器获取一个RPC回复XML,修改一些项,并生成一个最小的配置.xml,然后可以将其发送到服务器.
在修改图形用户界面中的值时,我将modified elements添加到一个集合中,以及它们的ancestor elements和sibling elements(不包含子对象),因为这将是"最小可行"结果文件的内容
我正在处理的示例(缩写)XML:
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:a1cfef75-dba4-4fdf-81eb-8d5f65d35511">
<data>
<bridges xmlns="urn:ieee:std:802.1Q:yang:ieee802-dot1q-bridge">
<bridge>
(...)
</bridge>
</bridges>
<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
<interface>
<name>PORT_0</name>
<description>random</description>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">ianaift:ethernetCsmacd</type>
<bridge-port xmlns="urn:ieee:std:802.1Q:yang:ieee802-dot1q-bridge">
(...)
</bridge-port>
</interface>
<interface>
(...)
</interface>
</interfaces>
<keystore xmlns="urn:ietf:params:xml:ns:yang:ietf-keystore">
(...)
</keystore>
</data>
</rpc-reply>
我在同时使用.iter()
和.remove()
时发现了一个问题,例如,当我想要修改<;Description>;时,它只删除<;Bridge>;分支,然后.iter()
循环不会返回到<;接口>;,或返回到它的直接祖先,这很可能是因为我已经删除了关于祖先的所有信息.换句话说,.iter().
循环在第一次遇到"最后一叶"元素时停止.
我正在使用以下代码来删除项目,self.itemstokeep
是一组etree.Element
以保留
for item in treecopy.iter():
if not item in self.itemstokeep:
if not item.getparent() == None:
item.getparent().remove(item)
else:
continue
Can you recommend any nice way to solve this or completely work around the problem?
The biggest difference from the answers I've found here so far is that I won't know which items to remove, only which ones to keep, and I won't always have the same input structure with exception of 2 top-level elements, which makes the usual 'xpath' approach complicated...
我也想过不再创建一个itemstokeep
的集合,而是在元素被修改时基本上重建一棵树,但如果这看起来像是一个非优化的解决方案,因为我需要总是判断祖先之间的重复项并多次遍历树-但可能我也遗漏了一些东西.