Python更改xml属性

2024-09-26 17:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

Python2 在以下情况下,是否可以使用python更改xml文件

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

按名称属性搜索然后更改位置?在


Tags: 文件name名称属性type情况positionxml
1条回答
网友
1楼 · 发布于 2024-09-26 17:42:05

您可以使用内置的^{}模块来解析XML,找到Label元素,并通过^{}属性更改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>'

请注意,属性的顺序不会被保留,根据定义,属性是无序的。在

相关问题 更多 >

    热门问题