简体   繁体   中英

Creating Dictionaries from XML Data in Python (with xml.etree.ElementTree)

I'm having similar difficulties to the one posed in this answered question , except the solution provided isn't working with my version of the problem.

With this sample XML data:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element>
        <name>XYZ</name>
        <value>789</value>
    </element>
    <element>
        <name>ABC</name>
        <value>123</value>
    </element>
</root>

My goal is to obtain a dictionary with the keys XYZ,ABC and the corresponding values 789,123. In other words, it should output the same as:

dict(XYZ=789,ABC=123)

Find element tags, and their name , value children using findall and find methods:

>>> import xml.etree.ElementTree as ET
>>>
>>> root = ET.fromstring('''<?xml version="1.0" encoding="UTF-8"?>
... <root>
...     <element>
...         <name>XYZ</name>
...         <value>789</value>
...     </element>
...     <element>
...         <name>ABC</name>
...         <value>123</value>
...     </element>
... </root>
... ''')
>>> {e.find('name').text: e.find('value').text for e in root.findall('element')}
{'XYZ': '789', 'ABC': '123'}

Another try may be using xpath and lxml.etree .

from lxml import etree

s="""<root>
    <element>
        <name>XYZ</name>
        <value>789</value>
    </element>
    <element>
        <name>ABC</name>
        <value>123</value>
    </element>
</root>"""
tree = etree.fromstring(s)
data = [(i.xpath("./name//text()")[0],i.xpath("./value//text()")[0]) for i in tree.xpath("//element")]
print {k:v for k,v in data}

Output-

{'XYZ': '789', 'ABC': '123'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM