如何在python中创建XML文件中的元素列表

时间:2013-09-02 14:02:37

标签: python xml

我的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列表的特定元素中读取文本是什么?

感谢

1 个答案:

答案 0 :(得分:0)

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] - 作者......