Python 解析 XML

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.html
import lxml
from lxml import etree

def 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

车斗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值