未按预期获得 XML 输出

Not getting XML output as expected

我有 Python3 并且正在学习这个 XML 教程,https://docs.python.org/3.7/library/xml.etree.elementtree.html

我希望输出所有 DailyIndexRatio 的列表

DailyIndexRatio {'CUSIP': '912810FD5','IssueDate': '1998-04-15', 
'Date':'2019-03-01','RefCPI':'251.23300','IndexRatio':'1.55331' }
 ....

而不是我的代码输出

DailyIndexRatio {}
 ....

如何修复?

这是代码

import xml.etree.ElementTree as ET

tree = ET.parse('CPI_20190213.xml')
root = tree.getroot()

print(root.tag)
print(root.attrib)

for child in root:
    print(child.tag,child.attrib)

我从 https://treasurydirect.gov/xml/CPI_20190213.xml

下载了 xml 文件

您正在打印属性,但该元素没有任何属性。

这是一个具有以下属性的元素:

<element name="Bob" age="40" sex="male" />

但是您尝试打印的元素没有这些。它有 个子元素:

<element>
    <name>Bob</name>
    <age>40</age>
    <sex>male</sex>
</element>
import xml.etree.ElementTree as ET

tree = ET.parse('CPI_20190213.xml') # Load the XML
root = tree.getroot() # Get XML root element
e = root.findall('.//DailyIndexRatio') # use xpath to find relevant elements
# for each element
for i in e:
    # create a dictionary object.
    d = {}
    # for each child of element
    for child in i:
        # add the tag name and text value to the dictionary
        d[child.tag] = child.text
    # print the DailyIndexRatio tag name and dictionary
    print (i.tag, d)

输出:

DailyIndexRatio {'CUSIP': '912810FD5', 'IssueDate': '1998-04-15', 'Date': '2019-03-01', 'RefCPI': '251.23300', 'IndexRatio': '1.55331'}
DailyIndexRatio {'CUSIP': '912810FD5', 'IssueDate': '1998-04-15', 'Date': '2019-03-02', 'RefCPI': '251.24845', 'IndexRatio': '1.55341'}
DailyIndexRatio {'CUSIP': '912810FD5', 'IssueDate': '1998-04-15', 'Date': '2019-03-03', 'RefCPI': '251.26390', 'IndexRatio': '1.55351'}
DailyIndexRatio {'CUSIP': '912810FD5', 'IssueDate': '1998-04-15', 'Date': '2019-03-04', 'RefCPI': '251.27935', 'IndexRatio': '1.55360'}
...