我有以下输入XML:
<host xmlns="urn:jboss:domain:4.1" >
<profile>
<subsystem xmlns="urn:jboss:domain:jmx:1.3">
<expose-resolved-model/>
<expose-expression-model/>
<remoting-connector/>
</subsystem>
</profile>
</host>
如您所见,xmlns用于两个名称空间,&#34; urn:jboss:domain:4.1&#34; 和&#34; urn:jboss:domain :JMX:1.3&#34;
我想在主机元素
中添加一个属性下面是我在Python中的代码:
from xml.etree import ElementTree as ET
def parse_xml():
ET.register_namespace('','urn:jboss:domain:4.1')
tree = ET.parse('sample.xml')
root = tree.getroot()
for elements in tree.iter():
if "host" in elements.tag :
elements.attrib['name'] = "slaveOne"
print elements.attrib
tree.write('sample.xml')
上面的代码更改了XML,如下所示:
<host xmlns="urn:jboss:domain:4.1" xmlns:ns1="urn:jboss:domain:jmx:1.3" name="slaveOne">
<profile>
<ns1:subsystem>
<ns1:expose-resolved-model />
<ns1:expose-expression-model />
<ns1:remoting-connector />
</ns1:subsystem>
</profile>
</host>
tree.write(&#39; sample.xml中&#39)
在这种情况下更改属于相同前缀的所有元素
ET.register_namespace(&#39;&#39;,&#39;瓮:JBoss的:域:4.1&#39)
答案 0 :(得分:0)
您可以尝试使用minidom:
from xml.dom import minidom
doc = minidom.parse("sample.xml")
#getElementsByTagName returns NodeList
#grab first
host = doc.getElementsByTagName("host")[0]
#set attr -> value
#look at setAttributeNS in minidom docs for namespaces
host.setAttribute('name', '123')
#write to file
with open('sample2.xml', 'w') as xmlfile:
doc.writexml(xmlfile)
请查看xml.sax个包和此XML Processing Modules页面。