简体   繁体   English

无法获得预期的XML输出

[英]Not getting XML output as expected

I have Python3 and am following this XML tutorial, https://docs.python.org/3.7/library/xml.etree.elementtree.html 我有Python3,并且正在关注此XML教程https://docs.python.org/3.7/library/xml.etree.elementtree.html

I wish to output a listing of all DailyIndexRatio 我希望输出所有DailyIndexRatio的列表

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

Instead my code outputs 相反,我的代码输出

DailyIndexRatio {}
 ....

How to fix? 怎么修?

Here is the code 这是代码

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)

And I downloaded the xml file from https://treasurydirect.gov/xml/CPI_20190213.xml 然后我从https://treasurydirect.gov/xml/CPI_20190213.xml下载了xml文件

You're printing the attributes, but that element does not have any attributes. 您正在打印属性,但是该元素没有任何属性。

This is an element with attributes: 这是一个具有属性的元素:

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

But the element you're trying to print doesn't have those. 但是您要打印的元素没有这些元素。 It has child elements : 它具有子元素

<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)

Outputs: 输出:

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'}
...

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

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