I have a program,But that not contain class concept ( Python program follow some value to class concept) am really a new one in python world. So learning from the original way help me out to shine in this world. Can anyone kindly help me out, instead of making this question negative mark 🙁
import xml.etree.ElementTree as ET
import sys
doc = ET.parse("books.xml")
root = doc.getroot()
root_new = ET.Element("books")
for child in root:
name = child.attrib['name']
cost = child.attrib['cost']
# create "book" here
book = ET.SubElement(root_new, "book")
book.set("name",name)
book.set("cost",cost)
if 'color' in child.attrib:
color = child.attrib['color']
book.set("color",color)
if 'weight' in child.attrib:
weight = child.attrib['weight']
book.set("weight",weight)
for g in child.findall("cover"):
# create "group" here
cover = ET.SubElement(cover,"cover")
if g.text != "goldcover":
cover.text = g.text
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
For understanding : my xml is ,
<books>
<book name="goodbook" cost="10" color="green"></book>
<book name="badbook" cost="1000" weight="100"><cover>papperback</cover><cover>hardcover</cover></book>
<book name="avgbook" cost="99" weight="120"></book>
</books>
As a fresher on python i hope some one will help me out , All valuable input are warmly welcomed.
Ok, this is not that hard of an exercise but I would go about this this way. You have a collection of books thus my class would be called
BookCollectionand it would take in the path to a XML file.Now, what you need is the following a method to
parsethe XML, a method togeta book, and a method toseta book. So, a skeleton class would look like:You do not need to represent a book as a class in python as that just over complicates the entire bit of a code thus the tuple. And, why I abstracted the XML file as a book collection.
I will not fill in the details beyond the skeleton so you can learn the rest from there.
EDIT:
As it appears you want to also output the XML I would add a
to_xmlmethod to the above class that will write out your XML. If you need to remove books I would also add the associated method, but that is up for your to implement.