http://python101.pythonlibrary.org/chapter23_xml.html
ElementTree
ElementTree
创建
- import xml.etree.ElementTree as xml
-
- def createXML(filename):
- """
- Create an example XML file
- """
- root = xml.Element("zAppointments")
- appt = xml.Element("appointment")
- root.append(appt)
-
- # add appointment children
- begin = xml.SubElement(appt, "begin")
- begin.text = "1181251680"
-
- uid = xml.SubElement(appt, "uid")
- uid.text = "040000008200E000"
-
- alarmTime = xml.SubElement(appt, "alarmTime")
- alarmTime.text = "1181572063"
-
- state = xml.SubElement(appt, "state")
-
- location = xml.SubElement(appt, "location")
-
- duration = xml.SubElement(appt, "duration")
- duration.text = "1800"
-
- subject = xml.SubElement(appt, "subject")
-
- tree = xml.ElementTree(root)
- with open(filename, "wb") as fh:
- tree.write(fh)
-
-
- if __name__ == "__main__":
- createXML("appt.xml")
解析
- import xml.etree.cElementTree as ET
-
- def parseXML(xml_file):
- """
- Parse XML with ElementTree
- """
- tree = ET.ElementTree(file=xml_file)
- print(tree.getroot())
- root = tree.getroot()
- print("tag=%s, attrib=%s" % (root.tag, root.attrib))
-
- for child in root:
- print(child.tag, child.attrib)
- if child.tag == "appointment":
- for step_child in child:
- print(step_child.tag)
-
- # iterate over the entire tree
- print("-" * 40)
- print("Iterating using a tree iterator")
- print("-" * 40)
- iter_ = list(tree.iter())
- for elem in iter_:
- print(elem.tag)
-
- # get the information via the children!
- print("-" * 40)
- print("Iterating using getchildren()")
- print("-" * 40)
- appointments = list(root)
- for appointment in appointments:
- appt_children = list(appointment)
- for appt_child in appt_children:
- print("%s=%s" % (appt_child.tag, appt_child.text))
-
- if __name__ == "__main__":
- parseXML("appt.xml")
-
- state = xml.SubElement(appt, "state")
-
- location = xml.SubElement(appt, "location")
-
- duration = xml.SubElement(appt, "duration")
- duration.text = "1800"
-
- subject = xml.SubElement(appt, "subject")
-
- tree = xml.ElementTree(root)
- with open(filename, "wb") as fh:
- tree.write(fh)
-
-
- if __name__ == "__main__":
- createXML("appt.xml")
评论
发表评论