Python 解析 XML
有xml如下(ftp://pub:[email protected]/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.html import lxml from lxml import etree def parseUrl(): repoXml = "ftp://pub:[email protected]/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