Element类型是一种灵活的容器对象,用于在内存中存储结构化数据。
[注意]xml.etree.ElementTree模块在应对恶意结构数据时显得并不安全。
每个element对象都具有以下属性:
1. tag:string对象,表示数据代表的种类。
2. attrib:dictionary对象,表示附有的属性。
3. text:string对象,表示element的内容。
4. tail:string对象,表示element闭合之后的尾迹。
5. 若干子元素(child elements)。
[注意]xml.etree.ElementTree模块在应对恶意结构数据时显得并不安全。
每个element对象都具有以下属性:
1. tag:string对象,表示数据代表的种类。
2. attrib:dictionary对象,表示附有的属性。
3. text:string对象,表示element的内容。
4. tail:string对象,表示element闭合之后的尾迹。
5. 若干子元素(child elements)。
<tag attrib1=1>text</tag>tail
1 2 3 4
Element中的遍历与查询
Element.iter(tag=None):遍历该Element所有后代,也可以指定tag进行遍历寻找。
Element.findall(path):查找当前元素下tag或path能够匹配的直系节点。
Element.find(path):查找当前元素下tag或path能够匹配的首个直系节点。
Element.text: 获取当前元素的text值。
Element.get(key, default=None):获取元素指定key对应的属性值,如果没有该属性,则返回default值。
tag:string,元素代表的数据种类。
text:string,元素的内容。
tail:string,元素的尾形。
attrib:dictionary,元素的属性字典。
#针对属性的操作
clear():清空元素的后代、属性、text和tail也设置为None。
get(key, default=None):获取key对应的属性值,如该属性不存在则返回default值。
items():根据属性字典返回一个列表,列表元素为(key, value)。
keys():返回包含所有元素属性键的列表。
set(key, value):设置新的属性键与值。
#针对后代的操作
append(subelement):添加直系子元素。
extend(subelements):增加一串元素对象作为子元素。#python2.7新特性
find(match):寻找第一个匹配子元素,匹配对象可以为tag或path。
findall(match):寻找所有匹配子元素,匹配对象可以为tag或path。
findtext(match):寻找第一个匹配子元素,返回其text值。匹配对象可以为tag或path。
insert(index, element):在指定位置插入子元素。
iter(tag=None):生成遍历当前元素所有后代或者给定tag的后代的迭代器。#python2.7新特性
iterfind(match):根据tag或path查找所有的后代。
itertext():遍历所有后代并返回text值。
remove(subelement):删除子元素。
实例
xml文件内容:<?xml version="1.0" encoding="utf-8"?>
<root>
<title>导购码接口测试</title>
<host>dgm.boweixin.com</host>
<port>80</port>
<No>[]</No>
<InterfaceList>
<params>
<name type="str">account</name>
<value>1</value>
<must>2</must>
</params>
<params>
<name type="int">userId</name>
<value>3</value>
<must>4</must>
</params>
<login>user_id</login>
<isList>0</isList><id>1001</id>
<name>登陆</name>
<method>POST</method>
<url>/Login</url>
<hope>{"appStatus":{"errorCode":0,"message":"操作成功"},"content":[{"user_sex":0,"fk_user_city":440300,"user_id":30,"nickname":"18576759587","user_phone":"18576759587","head_picture":"http:\/\/dgm.boweixin.com\/","has_finance":1,"user_state":1}]}</hope>
<login>user_id</login>
<isList>0</isList>
</InterfaceList>
<InterfaceList>
<params>
<name type="str">account</name>
<value>5</value>
<must>6</must>
</params>
<params>
<name type="int">userId</name>
<value>7</value>
<must>8</must>
</params>
<login>user_id</login>
<id>10012</id>
<name>登陆1</name>
<method>POST1</method>
<url>/Login1</url>
<hope>{"appStatus":{"errorCode":0,"message":"操作成功"},"content":[{"user_sex":0,"fk_user_city":440300,"user_id":30,"nickname":"18576759587","user_phone":"18576759587","head_picture":"http:\/\/dgm.boweixin.com\/","has_finance":1,"user_state":1}]}</hope>
<login>0</login>
<isList>0</isList>
</InterfaceList>
</root>
- 代码解析
from xml.etree import ElementTree as ET
def getXML(xml):
"""
"""
tree = ET.parse(xml)
root = tree.getroot()
i_base = {}
interfaceName = []
i_base["title"] = root.find("title").text
i_base["host"] = root.find("host").text
i_base["port"] = root.find("port").text
i_base["No"] = root.find("No").text
interfaceName.append(i_base)
for elem in root.findall("InterfaceList"):
i_app = {}
i_app["id"] = elem.find('id').text
i_app["name"] = elem.find('name').text
i_app["method"] = elem.find('method').text
i_app["url"] = elem.find('url').text
i_app["hope"] = elem.find('hope').text
i_app["login"] = elem.find('login').text
i_app["isList"] = elem.find('isList').text
interfaceName.append(i_app)
for p in elem.findall("params"):
print(p.find("name").attrib.get("type"))
print(p.find("value").text)
print(p.find("must").text)
# print(interfaceName)
return interfaceName
getXML("test4.xml")
转载:https://www.jianshu.com/p/96896b697ce4
(1)Parsing XML with lxml
xml文件内容如下:
xml文件内容如下:
<?xml version="1.0" ?>
<zAppointments reminder="15">
<appointment>
<begin>1181251680</begin>
<uid>040000008200E000</uid>
<alarmTime>1181572063</alarmTime>
<state></state>
<location></location>
<duration>1800</duration>
<subject>Bring pizza home</subject>
</appointment>
<appointment>
<begin>1234360800</begin>
<duration>1800</duration>
<subject>Check MS Office website for updates</subject>
<location></location>
<uid>604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800</uid>
<state>dismissed</state>
</appointment>
</zAppointments>
from lxml import etree
from StringIO import StringIO
#----------------------------------------------------------------------
def parseXML(xmlFile):
"""
Parse the xml
"""
f = open(xmlFile)
xml = f.read()
f.close()
tree = etree.parse(StringIO(xml))
context = etree.iterparse(StringIO(xml))
for action, elem in context:
if not elem.text:
text = "None"
else:
text = elem.text
print elem.tag + " => " + text
if __name__ == "__main__":
parseXML("example.xml")
(2)Parsing the Book Example
xml内容如下:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>
代码如下:
from lxml import etree
from StringIO import StringIO
#----------------------------------------------------------------------
def parseBookXML(xmlFile):
f = open(xmlFile)
xml = f.read()
f.close()
tree = etree.parse(StringIO(xml))
print tree.docinfo.doctype
context = etree.iterparse(StringIO(xml))
book_dict = {}
books = []
for action, elem in context:
if not elem.text:
text = "None"
else:
text = elem.text
print elem.tag + " => " + text
book_dict[elem.tag] = text
if elem.tag == "book":
books.append(book_dict)
book_dict = {}
return books
if __name__ == "__main__":
parseBookXML("example2.xml")
book_dict[elem.tag] = text
(3)Refactoring the Code:
from lxml import etree
#----------------------------------------------------------------------
def parseBookXML(xmlFile):
""""""
context = etree.iterparse(xmlFile)
book_dict = {}
books = []
for action, elem in context:
if not elem.text:
text = "None"
else:
text = elem.text
print elem.tag + " => " + text
book_dict[elem.tag] = text
if elem.tag == "book":
books.append(book_dict)
book_dict = {}
return books
if __name__ == "__main__":
parseBookXML("example.xml")
转载:http://www.blog.pythonlibrary.org/2010/11/20/python-parsing-xml-with-lxml/