Python 解析 XML

来源:互联网 发布:美服剑灵优化 编辑:程序博客网 时间:2024/06/16 12:01

Python 解析 XML

有xml如下(ftp://pub:pub@pepstack.com/cloudera/cdh/5/repodata/repomd.xml):

<repomd xmlns="http://linux.duke.edu/metadata/repo">  <data type="other">    <location href="repodata/other.xml.gz"/>    <checksum type="sha">28452556db60e44611fe64a07b7ea53c3b0f0b78</checksum>    <timestamp>1439501658</timestamp>    <open-checksum type="sha">f7ed84e4c507d3e77f27caad68a8de1139b70252</open-checksum>  </data>  <data type="filelists">    <location href="repodata/filelists.xml.gz"/>    <checksum type="sha">d04b57b524c6dad1c330050b448ee4d9a0e5b3cf</checksum>    <timestamp>1439501658</timestamp>    <open-checksum type="sha">739432e431e0818ddaab99e5a54960e46730d4d9</open-checksum>  </data>  <data type="primary">    <location href="repodata/primary.xml.gz"/>    <checksum type="sha">a4f19bd70826bd8482069ede0b577c921bed726f</checksum>    <timestamp>1439501658</timestamp>    <open-checksum type="sha">9b8b1ada2695e39f2a3ef3108d34a0ddf1d7c3c8</open-checksum>  </data></repomd>

如果要解析出 primary的href的内容,可以:

# http://infohost.nmt.edu/tcc/help/pubs/pylxml/pylxml.pdf# http://lxml.de/tutorial.htmlimport lxmlfrom lxml import etreedef parseUrl():    repoXml = "ftp://pub:pub@pepstack.com/cloudera/cdh/5/repodata/repomd.xml"    ns = {'xmlns': 'http://linux.duke.edu/metadata/repo'}    parser = etree.XMLParser(ns_clean = True)    tree   = etree.parse(repomdXml, parser)    xmlstring = etree.tostring(tree, pretty_print=True, method="xml")    print xmlstring    primaryUrl = tree.xpath('/xmlns:repomd/xmlns:data[@type="primary"]/xmlns:location/@href', namespaces=ns)[0]    print primaryUrl

结果:

repodata/primary.xml.gz

原创粉丝点击