python使用libxml2 xpath解析xml,libxml2xpath,libxml2包可以方便


libxml2包可以方便的解析xml,但是安装起来不是很方便,尤其是windows上的安装,需要到 http://www.lfd.uci.edu/~gohlke/pythonlibs/ 搜索libxml2然后下载对应的文件安装。

下面是一个libxml2解析xml的示例:

要解析的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>

python代码如下:

import libxml2def text() :  doc = libxml2.parseFile('/tmp/books.xml')  for book in doc.xpathEval('/books/book') :        print book.content  doc.freeDoc()

评论关闭