Python XML 解析 ElementTree 复杂 XML 结构

2 投票
1 回答
1072 浏览
提问于 2025-04-18 11:35

我现在需要在Python中解析一个XML文档。不过,我在使用Python库和处理这个相对复杂的XML时遇到了困难。

我查看了这里的方法:使用ElementTree读取复杂的XML,但似乎并不奏效?

我使用的是Python 2.7.7。

这个XML文件来自于http://nvd.nist.gov/download.cfm#CURRENTXML,比如说,我需要解析的一个条目看起来是这样的: http://pastebin.com/qdPN98VX

我目前的相关代码大致是这样的。 我可以成功读取第一个条目的ID,但元素内部的内容无法访问。我也不确定对于一个50MB的文件,使用ElementTree是否是最佳选择?

from vulnsdb.models import Vuln as CVE


file = 'CVE/20140630-NVDCE-2.0-2014.xml'

tree = ET.parse(file)
root = tree.getroot()

for entry in root:
    c = CVE()
    c.name = entry.attrib['id']
    for details in entry:
        if details.find("{http://scap.nist.gov/schema/vulnerability/0.4}cve-id"):
            print details.find("{http://scap.nist.gov/schema/vulnerability/0.4}cve-id").text
    break

1 个回答

2

你可以使用 xml.etree.ElementTree.iterparse() 这个方法,它可以逐步解析树形结构:

import xml.etree.ElementTree as ET


TAG = '{http://scap.nist.gov/schema/feed/vulnerability/2.0}entry'
ID = "CVE-2014-0001"

tree = ET.iterparse(open('CVE/20140630-NVDCE-2.0-2014.xml'))
for event, element in tree:
    if event == 'end' and element.tag == TAG and element.attrib.get('id') == ID:
        print ET.tostring(element)
        break

撰写回答