【问题标题】:Python parsing multiple xml tagsPython解析多个xml标签
【发布时间】:2014-10-23 13:07:04
【问题描述】:

我发现元素树有点压倒性。我有一个 xml 文件,我有两个标签,我想获取标签的内容并使用它们制作一个 txt 文件。这两个标签是

<l>...</l>, 

<bib>...</bib>. 

有没有简单的方法来简单地抓取这两个标签中的内容?我可以很好地处理输出,我只是在 python 中处理 xml。

谢谢

【问题讨论】:

  • 所以人们正在忽略这个问题,因为我不知道如何做一些简单的事情?我可以添加所有用于读取和输出文本文件的代码,但这真的有必要吗?

标签: python xml text


【解决方案1】:

在您掌握它之前,解析 XML 文件可能具有挑战性。首先,您需要访问您想要的标签所属的“节点”。为此,您需要确定它们在 XML 层次结构中的位置。

假设这两个标签都没有嵌套很深并且位于树的第 2 级:

import xml.etree.ElementTree as ET
root = ET.parse(filename).getroot()

# The dot represents current nested level from root, else you must include other parent tags here
l_list = []
for node in root.findall("./l"):
    # tag.text is the attribute for the text between the tag
    l_list.append(node.text)

bib_list = []
for node in root.findall("./bib"):
    bib_list.append(node.text)

一个真实的例子涉及解析 Nessus 扫描文件。在这种情况下,所需的发现嵌套得更深。获取这些的高级摘要如下(假设一台主机,多台主机会更复杂,因为您将枚举每个主机以查找结果):

import xml.etree.ElementTree as ET
root = ET.parse(filename).getroot()

findings = []
one_finding = {}
ReportItems = root.findall("./Report/ReportHost/ReportItem")
for node in ReportItems:
    for n in ReportItems.getchildren()
        # Save all child tags as dictionary of tag_name:tag_text
        one_finding[node.tag] = node.text
    findings.append(one_finding)

我希望这个例子也有助于展示如何创建一个标签名称及其文本的字典,然后将它们全部附加到一个嵌套字典列表中,以防你需要将它与你正在解析的内容一起使用。

【讨论】:

    【解决方案2】:

    我不确定您是否听说过Beautifulsoup,但我相信它对于此类任务非常有用。当然,有多种方法可以完成您的要求,我将使用Beautifulsoup 进行解释。您可以找到文档here

    安装:pip install beautifulsoup4

    from bs4 import BeautifulSoup
    
    my_xml='''<CATALOG>
    <PLANT>
    <COMMON>Bloodroot</COMMON>
    <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
    <ZONE>4</ZONE>
    <LIGHT>Mostly Shady</LIGHT>
    <PRICE>$2.44</PRICE>
    <AVAILABILITY>031599</AVAILABILITY>
    </PLANT>
    </CATALOG>'''
    
    souped=BeautifulSoup(my_xml, 'xml')
    
    >>> print souped.find("COMMON").text  # Finds the first instance
    Bloodroot
    
    >>> _commons = souped.findAll("COMMON")  # Returns a list of all instances
    >>> print _commons[0].text
    Bloodroot
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多