简体   繁体   English

如何使用 ElemenTree 在 Python 中读取 XML 文件?

[英]How to use ElemenTree for reading XML files in Python?

I've got an XML file which looks like this:我有一个如下所示的 XML 文件:

<?xml version="1.0"?>
-<Object>
    <ID>Object_01</ID>
    <Location>Manchester</Location>
    <Date>01-01-2020</Date>
    <Time>15u59m05s</Time>   
-<Max_25Hz>
    <25Hz>0.916631065043311</25Hz>
    <25Hz>0.797958008447961</25Hz>
</Max_25Hz>
-<Max_75Hz>
    <75Hz>1.96599232706463</75Hz>
    <75Hz>1.48317837078523</75Hz>
</Max_75Hz>
</Object>

I still don't really understand the difference between attributes and text .我还是不太明白attributestext之间的区别。 With below code I tried to receive all the values using text .使用下面的代码,我尝试使用text接收所有值。

import xml.etree.ElementTree as ET

root = r'c:\data\FF\Desktop\My_files\XML-files\Object_01.xml'

tree = ET.parse(root)
root = tree.getroot()

for elem in root:
    for subelem in elem:
        print(subelem.text) 

Expected output:预期输出:

Object_01
Manchester
01-01-2020
15u59m05s
0.916631065043311
0.797958008447961
1.96599232706463
1.48317837078523

Received output:接收输出:

0.916631065043311
0.797958008447961
1.96599232706463
1.48317837078523

I tried to do to same with .attributes in the hope to receive all the 'column' names but then I received:我试图对.attributes做同样的事情,希望能收到所有的“列”名称,但后来我收到了:

{}
{}
{}
{}

You can access them directly above the for-loop.您可以直接在 for 循环上方访问它们。

Ex:前任:

tree = ET.ElementTree(ET.fromstring(X))
root = tree.getroot()

for elem in root:
    print(elem.text)       #! Access them Here
    for subelem in elem:
        print(subelem.text) 

Output:输出:

Object_01
Manchester
01-01-2020
15u59m05s

        
0.916631065043311
0.797958008447961

        
1.96599232706463
1.48317837078523

You could give a try to https://github.com/martinblech/xmltodict .您可以尝试https://github.com/martinblech/xmltodict It is almost a replacement for json module.它几乎是 json 模块的替代品。 This allows to read an xml file into a python dict .这允许将 xml 文件读入 python dict This simplifies greatly accessing the xml content.这极大地简化了对 xml 内容的访问。

Something like:就像是:

from xmldict import *

root = r'c:\data\FF\Desktop\My_files\XML-files\Object_01.xml'
with open(root) as file:
   xmlStr = file.read()
   xmldict = xml.parse(xmlStr)

print (xmldict['Object']['Id'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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