<pre name="code" class="python">#!/usr/bin/env python
# encoding: utf-8
from xml.etree import ElementTree as tree
# 注意, 在xml的最前端 即<?xml version="1.0" encoding="UTF-8"?>前面不能有空格
xmlstr = """<?xml version="1.0" encoding="utf-8"?>
<root>
<person age="18">
<name>hzj</name>
<sex>man</sex>
</person>
<person age="19" des="hello">
<name>kiki</name>
<sex>female</sex>
</person>
</root>
"""
def print_node(node, search_attr):
print node.attrib
if node.attrib.has_key(search_attr):
print node.attrib[search_attr]
print "node.tag", node.tag
print "node.text", node.text
def read_xml(text):
root = tree.fromstring(text)
person_node = root.getiterator("person")
for node in person_node:
print node.attrib
person_node_childlist = person_node[0].getchildren()
for child in person_node_childlist:
print child.tag, child.text
person_attr = "age"
print_node(person_node_childlist[0], person_attr)
def test_find():
root = tree.fromstring(xmlstr)
personnode = root.find("person")
print_node(personnode, "age")
def test_findall():
root = tree.fromstring(xmlstr)
namelist = root.findall("person/name")
for e in namelist:
print e.tag, e.text
read_xml(xmlstr)
test_find()
test_findall()
python 处理 xml
最新推荐文章于 2024-07-09 15:20:18 发布