我有一个程序,但它不包含类概念(Python 程序遵循一些对类概念的价值)真的是 python 世界中的一个新程序。所以从原始的方式中学习帮助我在这个世界上闪耀。任何人都可以帮助我,而不是把这个问题打成负号:(
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)
为了理解:我的 xml 是,
<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>
作为python的新手,我希望有人能帮助我,热烈欢迎所有有价值的意见。