我终于决定学习如何在 python 中解析 xml。我使用 elementtree 只是为了获得基本的理解。我在 CentOS 6.5 上使用 python 2.7.9。我浏览了以下页面:
http://www.diveintopython3.net/xml.html
https://pymotw.com/2/xml/etree/ElementTree/parse.html#traversing-the-parsed-tree
并在这个论坛上进行了几次搜索,但我遇到了一些麻烦,我不确定这是我的代码还是我试图解析的 xml。
我需要能够验证某些元素是否在 xml 中。例如,在下面的 xml 中,我需要检查元素 Analyzer 是否存在,如果存在,则获取属性。然后,如果 Analyzer 存在,我需要检查 location 元素并获取文本,然后是 name 元素并获取该文本。我认为下面的代码会检查元素是否存在:
if element.find('...') is not None
但这会产生不一致的结果,并且它似乎永远找不到位置或名称元素。例如:
if tree.find('Alert') is not None:
似乎工作,但
if tree.find('location') is not None:
或者
if tree.find('Analyzer') is not None:
绝对不行。我猜 tree.find() 函数只适用于顶层?
那么我该如何做这个检查呢?
这是我的xml:
<?xml version='1.0' encoding='UTF-8'?>
<Report>
<Alert>
<Analyzer analyzerid="CS">
<Node>
<location>USA</location>
<name>John Smith</name>
</Node>
</Analyzer>
<AnalyzerTime>2016-06-11T00:30:02+0000</AnalyzerTime>
<AdditionalData type="integer" meaning="number of alerts in this report">19</AdditionalData>
<AdditionalData type="string" meaning="report schedule">5 minutes</AdditionalData>
<AdditionalData type="string" meaning="report type">alerts</AdditionalData>
<AdditionalData type="date-time" meaning="report start time">2016-06-11T00:25:16+0000</AdditionalData>
</Alert>
<Alert>
<CreateTime>2016-06-11T00:25:16+0000</CreateTime>
<Source>
<Node>
<Address category="ipv4-addr">
<address>1.5.1.4</address>
</Address>
</Node>
</Source>
<Target>
<Service>
<port>22</port>
<protocol>TCP</protocol>
</Service>
</Target>
<Classification text="SSH scans, direction:ingress, confidence:80, severity:high">
<Reference meaning="Scanning" origin="user-specific">
<name>SSH Attack</name>
<url> </url>
</Reference>
</Classification>
<Assessment>
<Action category="block-installed"/>
</Assessment>
<AdditionalData type="string" meaning="top level domain owner">PH, Philippines</AdditionalData>
<AdditionalData type="integer" meaning="alert threshold">0</AdditionalData>
</Alert>
</Report>
这是我的代码:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for child in root: print child
all_links = tree.findall('.//Analyzer')
try:
print all_links[0].attrib.get('analyzerid')
ID = all_links[0].attrib.get('analyzerid')
all_links2 = tree.findall('.//location')
print all_links2
try:
print all_links[0].text
except: print "can't print text location"
if tree.find('location') is None: print 'lost'
for kid in tree.iter('location'):
try:
location = kid.text
print kid.text
except: print 'bad'
except IndexError: print'There was no Analyzer element'