Python解析多个xml标记

Python解析多个xml标记,python,xml,text,Python,Xml,Text,我发现元素树有点势不可挡。我有一个xml文件和两个标记,我想获取标记的内容并用它们生成一个txt文件。这两个标签是 <l>...</l>, 。。。, 及 。。。。 有没有一种简单的方法可以简单地抓取这两个标签中的内容?我可以很好地处理输出,我只是在python中处理xml时有些动摇 谢谢我不确定您是否听说过Beautifulsoup,但我相信它对这类任务非常有用。当然,有多种方法可以实现您的要求,我将使用beautifulsou来解释。您可以找到文档 安装:pip

我发现元素树有点势不可挡。我有一个xml文件和两个标记,我想获取标记的内容并用它们生成一个txt文件。这两个标签是

<l>...</l>, 
。。。,

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


谢谢

我不确定您是否听说过Beautifulsoup,但我相信它对这类任务非常有用。当然,有多种方法可以实现您的要求,我将使用
beautifulsou
来解释。您可以找到文档

安装:
pip安装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
从bs4导入美化组
我的xml=“”
血根
美洲血根草
4.
大部分是阴凉的
$2.44
031599
'''
souped=BeautifulSoup(我的xml,'xml')
>>>print souped.find(“COMMON”).text#查找第一个实例
血根
>>>_commons=souped.findAll(“COMMON”)#返回所有实例的列表
>>>打印_commons[0]。文本
血根

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()

# 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)
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)