通过lxml python更改xml中的属性值

时间:2017-02-27 10:32:05

标签: python xml lxml

这是我的xml:

<request><table attributeA="50" attributeB="1"></table>........</request>

如何更新attributeA的值,以获得类似attributeA =“456”

的内容
<request><table attributeA="456" attributeB="1"></table>........</request>

1 个答案:

答案 0 :(得分:2)

使用etree和xpath:

>>> from lxml import etree
>>> xml = '<request><table attributeA="50" attributeB="1"></table></request>'
>>> root = etree.fromstring(xml)
>>> for el in root.xpath("//table[@attributeA]"):
...     el.attrib['attributeA'] = "456"
...
>>> print etree.tostring(root)
<request><table attributeA="456" attributeB="1"/></request>