BeautifulSoup是一个很强大的HTML/XML解析工具,简单易用。不过从性能上来说,它可能并不是最好的。因此,我们考虑使用另外一个第三方包lxml,它在底层是通过C实现的,因此在速度上会有明显的优势。
还是之前的例子:
<?xml version="1.0" encoding="utf-8"?> <CSubmitState xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/"> <State>0</State> <MsgID>1311211532361125903</MsgID> <MsgState>提交成功</MsgState> <Reserve>0</Reserve> </CSubmitState>
唯一的区别当然就是这次用lxml来解析:
>>> root = etree.fromstring(xml) >>> root <Element {http://tempuri.org/}CSubmitState at 0x285fdc8>
在之前利用ElementTree解析的时候,我们遇到比较麻烦的地方就是去得到命名空间。而这里,lxml提供了一个nsmap方法则让这个问题的处理方便了不少:
>>> root.nsmap {'xsi': 'http://www.w3.org/2001/XMLSchema-instance', None: 'http://tempuri.org/', 'xsd': 'http://www.w3.org/2001/XMLSchema'}
再观察之前的XML文件,可以看出所需的节点都使用的是默认namespace,即{None: 'http://tempuri.org/'}。接下来?我想不用说了。如果不清楚可以参考ElementTree这篇博客。