簡體   English   中英

Python更改XML屬性

[英]Python change xml attribute

Python 2是否可以在以下情況下使用python更改xml文件?

<Label name="qotl_type_label" position="910,980" font="headline_light" />

按名稱搜索屬性,然后更改位置?

您可以使用內置的xml.etree.ElementTree模塊來解析XML,找到Label元素並通過.attrib屬性更改position屬性:

>>> import xml.etree.ElementTree as ET
>>>
>>> s = '<root><Label name="qotl_type_label" position="910,980" font="headline_light" /></root>'
>>>
>>> root = ET.fromstring(s)
>>> label = root.find(".//Label[@name='qotl_type_label']")
>>> label.attrib['position'] = 'new,position'
>>> ET.tostring(root)
'<root><Label font="headline_light" name="qotl_type_label" position="new,position" /></root>'

請注意,屬性的順序不保留, 定義不按順序對屬性進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM