【问题标题】:Get all the Text from a xml file [duplicate]从 xml 文件中获取所有文本 [重复]
【发布时间】:2019-08-07 10:55:01
【问题描述】:

我想用 Python 提取 XML 文件中的所有文本。

有没有可能?

我听说可以使用 xml.etree.ElementTree

例如:

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

我只想提取: 1 2008年 141100 4 2011 等等……

【问题讨论】:

    标签: python xml text


    【解决方案1】:

    希望对你有帮助

    from xml-etree.ElementTree import parse
    
    tree = parse('data.xml') #extract the file (change the name to your file name)
    
    for e in tree.findall('year') #searches the content of all the tags 'year' 
        print(e.text)
    

    您还可以将值存储在字典中,键等于国家/地区名称,值等于所有属性的列表

    【讨论】:

    • 不起作用。 open 应该是 parse。并且问题中的 XML 文档中没有 title 元素。
    • 'title' 只是我输入的一个随机名称。在您的情况下,您可以输入排名、年份、邻居等。
    • 对不起,我是从我不久前制作的旧脚本中截取的。
    • 代码仍有至少两个语法错误。为什么不在发帖前测试一下?
    猜你喜欢
    • 2013-07-06
    • 1970-01-01
    • 2022-01-13
    • 2013-01-30
    • 2011-08-07
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多