python中使用xpath解析xml,pythonxpath解析xml,使用minidom很方便


使用minidom很方便,但是没有xpath的支持,可以通过下载 http://py-dom-xpath.googlecode.com/files/py-dom-xpath-0.1.tar.gz来让minidom支持xpath。

下载文件之后解压,然后切换到解压的目录,运行python setup.py install即可装上xpath。

如下是几个使用xpath的代码示例:

解析的xml如下:

<books>  <book isbn="123456">    <title>Moby Dick</title>    <author>Herman Melville</author>    <categories>      <category>Fiction</category>      <category>Adventure</category>    </categories>  </book>  <book isbn="98765643">    <title>The Decline and Fall of the Roman Empire</title>    <author>Edward Gibbon</author>    <category>      <category>History</category>      <category>Ancient</category>    </categories>  </book>  ...</books>

例一

import xpathimport xml.dom.minidomxml = xml.dom.minidom.parse('/tmp/books.xml')doc = xml.documentElementxpath.find('/books/book[1]', doc)[0].toxml()xpath.find('/books', doc)

例二

pythonimport xpathimport xml.dom.minidomxml = xml.dom.minidom.parse('/tmp/books.xml')doc = xml.documentElementcontext = xpath.XPathContext()context.variables['max'] = 100context.variables['min'] = 4context.findvalues('//book[price>=$min and price<=$max]', doc)

评论关闭