【问题标题】:How to loop over tags in XML file using python如何使用python循环XML文件中的标签
【发布时间】:2020-03-30 20:37:11
【问题描述】:

我的 XML 文件结构是:

<tp:Package xml:lang='en-US' xmlns:tp='http://myorg.org/2016/mypackage'>
    <tp:identifier>http://www.myweb.com/</tp:identifier>
    <tp:name>MyName</tp:name>
    <tp:description xml:lang='en-US'>My Description</tp:description>
    <tp:version>2020-01-01</tp:version>
    <tp:license href='http://www.myweb.com/terms/TermsConditions.html' name='Terms and Conditions' />
    <tp:publisher>MyPublisher</tp:publisher>
    <tp:publisherURL>http://www.mypublisherurl.com/</tp:publisherURL>
    <tp:publisherCountry>US</tp:publisherCountry>
    <tp:publicationDate>2020-01-01</tp:publicationDate>
    <tp:entryPoints>
        <tp:entryPoint>
            <tp:name>Form A</tp:name>
            <tp:description>This is Form A.</tp:description>
            <tp:version>v313</tp:version>
            <tp:entryPointDocument href='http://www.myweb.com/myfile.xsd' />
            <tp:formType>1</tp:formType>
        </tp:entryPoint>
        <tp:entryPoint>
            <tp:name>Form B</tp:name>
            <tp:description>This is Form B.</tp:description>
            <tp:version>v313</tp:version>
            <tp:entryPointDocument href='http://www.myweb.com/myfile.xsd' />
            <tp:formType>2</tp:formType>
        </tp:entryPoint>   
    </tp:entryPoints>
</tp:Package>

如何使用 etree 读取此文件并遍历每个 标签并打印元素 tp:name, tp:description, tp:version, tp:entryPointDocument, tp 的值:表单类型

以下是我的部分python代码:

from lxml import etree
tree = etree.parse(xmlfilepath)
root = tree.getroot()
for elt in root.xpath("//tp:entryPoints", namespaces={'tp': 'http://myorg.org/2016/mypackage'}):
    print(elt)

【问题讨论】:

    标签: python xpath lxml


    【解决方案1】:

    试试这个:

    package = """your xml above"""    
    from lxml import etree    
    tree = etree.fromstring(package)
    
    for elt in tree.xpath("//tp:entryPoints//*", namespaces={'tp': 'http://myorg.org/2016/mypackage'}):
        print(elt.text)
    

    输出:

    Form A
    This is Form A.
    v313
    None
    1
    
    
    Form B
    This is Form B.
    v313
    None
    2
    

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2013-08-26
      • 2016-07-08
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多