使用python时如何将附加属性添加到xml

时间:2019-08-13 15:23:32

标签: python json xml xml-parsing

我有以下格式的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

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

2 个答案:

答案 0 :(得分:1)

下面-您只需要找到元素并将新条目添加到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>'

答案 1 :(得分:0)

该方法的实现如下。

def add_to_xml(root)
    for el in root:
        if len(list(el)):    # check if element has child nodes
            status = root.find('.//status')
            status.attrib['Location'] = 'No Location'
            add_to_xml(el)

将“位置”添加到状态节点。