向SubElement添加属性

时间:2019-03-15 03:19:03

标签: python xml

我试图从两个打印命令中获得相同的输出,但是我没有想出在nc:operation="remove"之后插入shutdown的方法

#!/usr/bin/env python

from lxml import etree

config = """
<config>
  <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg">
    <interface-configuration>
      <interface-name>GigabitEthernet0</interface-name>
      <shutdown nc:operation="remove"></shutdown>
    </interface-configuration>
  </interface-configurations>
</config>
"""

# build xml
config_e = etree.Element("config")
interface01 = etree.SubElement(config_e, "interface-configurations", nsmap = {None: 'http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg'})
interface01_cfg = etree.SubElement(interface01, "interface-configuration")
etree.SubElement(interface01_cfg, "interface-name").text = 'GigabitEthernet0'
etree.SubElement(interface01_cfg, "shutdown")

print '======================================================================'
print config
print '======================================================================'
print etree.tostring(config_e, pretty_print=True)
print '======================================================================'

这是abobo python脚本的结果。

======================================================================
<config>
  <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg">
    <interface-configuration>
      <interface-name>GigabitEthernet0</interface-name>
      <shutdown nc:operation="remove"></shutdown>
    </interface-configuration>
  </interface-configurations>
</config>
======================================================================
<config>
  <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg">
    <interface-configuration>
      <interface-name>GigabitEthernet0</interface-name>
      <shutdown/>
    </interface-configuration>
  </interface-configurations>
</config>    
======================================================================

0 个答案:

没有答案