Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

how to create a list of elements from an XML file in python

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

I'm using etree in python

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

were the list of elements i would like to receive is

BookInfo = [title,author,year,price]

2) how would it be corect to read the Text in a specific elemnt of the list BookInfo

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Try this:

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)if you can receive the specific element from the list use BookInfo[0] - this is title, BookInfo[1] - author...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...