Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...