首页 > 解决方案 > 使用python时如何向xml添加附加属性

问题描述

我有以下格式的 xml。正如我们在下面看到的,我要添加到 xml 的新属性location=""<status> tag.

我不确定如何做到这一点。

<?xml version="1.0" encoding="UTF-8" ?>
<Buildings>
        <FloorPlan id= "1.23">
            <InfoList>
                <state id = "0" val= "0" location=""/>              
            </InfoList>
                <OwnerA id = "1.87">
                <InfoList>
                     <status id = "1" val= "0" location=""/>
                </InfoList>             
               </OwnerA >           
        </FloorPlan>
</Buildings>

我的代码实现现在如下。

def add_attrib_to_xml():
    with open("xmlconfig.xml") as xmlConfigFile:
        xmlConfigFile = ET.parse(target)

    root = xmlConfigFile.getroot()

    location_attrib = ET.Element("location")  # Create `location` attribute to add 
    location_attrib.text = "No location"

    add_to_xml(root, location_attrib ) # TODO: yet to implement

def add_to_xml(root, location_attrib)
   # Not sure on how to do it

任何帮助,将不胜感激。谢谢大家。:)

标签: pythonjsonxmlxml-parsing

解决方案


下面 - 你只需要找到元素并向attrib 字典添加一个新条目

import xml.etree.ElementTree as ET

xmlstring = '''<?xml version="1.0" encoding="UTF-8" ?>
<Buildings>
        <FloorPlan id= "1.23">
            <InfoList>
                <state id = "0" val= "0" location=""/>              
            </InfoList>
                <OwnerA id = "1.87">
                <InfoList>
                     <status id = "1" val= "0" location=""/>
                </InfoList>             
               </OwnerA >           
        </FloorPlan>
</Buildings>'''


root = ET.fromstring(xmlstring)
status = root.find('.//status')
status.attrib['location'] = 'No location'
tree_as_str = ET.tostring(root, encoding='utf8', method='xml')
print(tree_as_str)

输出

b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n<Buildings>\n        <FloorPlan id="1.23">\n            <InfoList>\n                <state id="0" location="" val="0" />              \n            </InfoList>\n                <OwnerA id="1.87">\n                <InfoList>\n                     <status id="1" location="No location" val="0" />\n                </InfoList>             \n               </OwnerA>           \n        </FloorPlan>\n</Buildings>'

推荐阅读