如何测试某个XML中是否存在属性

Jay*_*Jay 12 python xml lxml

我有一些XML,我通过lxml在python中解析.

我遇到的情况是某些元素具有属性而某些元素没有属性.

我需要提取它们,如果它们存在,但如果它们不存在则跳过它们 - 我目前正在着陆时出错(因为我的方法是错误的......)

我已部署了testfornull,但在所有情况下都不起作用:

码:

if root[0][a][b].attrib == '<>': 
 ByteSeqReference = "NULL"
else:
 ByteSeqReference = (attributes["Reference"])
Run Code Online (Sandbox Code Playgroud)

XML A:

<ByteSequence Reference="BOFoffset">
Run Code Online (Sandbox Code Playgroud)

XML B:

<ByteSequence Endianness = "little-endian" Reference="BOFoffset">
Run Code Online (Sandbox Code Playgroud)

XML C:

<ByteSequence Endianness = "little-endian">
Run Code Online (Sandbox Code Playgroud)

XML D:

 <ByteSequence>
Run Code Online (Sandbox Code Playgroud)

我目前的方法只能处理A,B或D.它无法应付C.

Cha*_*ffy 23

我很惊讶,对经常将不存在作品的属性空值测试 -什么,你应该做的是检查它是否存在,而不是它是否是空的:

if 'Reference' in current_element.attrib:
  ...do something with it...
Run Code Online (Sandbox Code Playgroud)