【问题标题】:how to create a list of elements from an XML file in python如何在python中从XML文件创建元素列表
【发布时间】:2013-09-02 14:02:36
【问题描述】:

我的 XML

<root>
- <Book category="Children">
  <title>Harry Potter</title> 
  <author>J.K</author> 
  <year>2005</year> 
  <price>29.99</price> 
  </Book>
- <Book category="WEB">
  <title>Learning XML</title> 
  <author>Erik T. Ray</author> 
  <year>2003</year> 
  <price>39.95</price> 
  </Book>
</root>

我在 python 中使用 etree

import xml.etree.ElementTree as ET
Books = ET.parse('4.xml') #parse the xml file into an elementtre

我想收到的元素列表是

BookInfo = [书名、作者、年份、价格]

2) 如何正确阅读列表 BookInfo 的特定元素中的文本

谢谢

【问题讨论】:

    标签: python xml


    【解决方案1】:

    1) 试试这个:

    import xml.etree.ElementTree as ET
        Books = ET.parse('4.xml') #parse the xml file into an elementtre
        root = Books.getroot()
        for child in root:
            BookInfo = [
            child.find('title').text,
            child.find('author').text,
            child.find('year').text,
            child.find('price').text
            ]
            print (BookInfo)
    


    2)如果您可以从列表中接收特定元素,请使用 BookInfo[0] - 这是标题,BookInfo[1] - 作者...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2015-10-31
      相关资源
      最近更新 更多