如何在 if 语句中测试 XML 标签属性的值
How to test value of XML tag attribute within an if statement
是否可以测试 XML
标签属性的 value
作为 if
语句的一部分?
例如,我有一个带有以下标签的 XML
:
<Cell ss:StyleID="HeadTableTitle" ss:MergeAcross="1"><Data ss:Type="String">Administrative Data</Data></Cell>
我正在尝试测试该 <Cell>
标签中的属性 ss:StyleID
== HeadTableTitle
是否
from lxml import etree
f_path = 'data store/cortex_full.xml' # enter path of xml file
epoch = 0 # set epoch window size (seconds) for smoothing data (set to 0 to use raw)
with open(f_path, 'r', encoding='utf-8') as f:
root = etree.parse(f)
namespaces = {'o': 'urn:schemas-microsoft-com:office:office',
'x': 'urn:schemas-microsoft-com:office:excel',
'ss': 'urn:schemas-microsoft-com:office:spreadsheet'}
ws = root.xpath('/ss:Workbook/ss:Worksheet', namespaces=namespaces)
if len(ws) > 0:
tables = ws[0].xpath('./ss:Table', namespaces=namespaces)
if len(tables) > 0:
rows = tables[0].xpath('./ss:Row', namespaces=namespaces)
for row in rows:
cells = row.xpath('./ss:Cell', namespaces=namespaces)
if len(cells) == 1: # skip if row have multiple 'cells'
if cells[0].attrib('./@ss:StyleID', namespaces=namespaces) == 'HeadTableTitle':
## execute some code ##
但是,当我执行代码的最后一行时,它会抛出 TypeError: 'lxml.etree._Attrib' object is not callable
要获取属性的值,您可以使用element.attrib['key']
或element.get('key')
。
在这两种情况下,如果属性绑定到命名空间,则您需要使用完整的命名空间 URI。
if cells[0].get('{urn:schemas-microsoft-com:office:spreadsheet}StyleID') == 'HeadTableTitle':
是否可以测试 XML
标签属性的 value
作为 if
语句的一部分?
例如,我有一个带有以下标签的 XML
:
<Cell ss:StyleID="HeadTableTitle" ss:MergeAcross="1"><Data ss:Type="String">Administrative Data</Data></Cell>
我正在尝试测试该 <Cell>
标签中的属性 ss:StyleID
== HeadTableTitle
是否
from lxml import etree
f_path = 'data store/cortex_full.xml' # enter path of xml file
epoch = 0 # set epoch window size (seconds) for smoothing data (set to 0 to use raw)
with open(f_path, 'r', encoding='utf-8') as f:
root = etree.parse(f)
namespaces = {'o': 'urn:schemas-microsoft-com:office:office',
'x': 'urn:schemas-microsoft-com:office:excel',
'ss': 'urn:schemas-microsoft-com:office:spreadsheet'}
ws = root.xpath('/ss:Workbook/ss:Worksheet', namespaces=namespaces)
if len(ws) > 0:
tables = ws[0].xpath('./ss:Table', namespaces=namespaces)
if len(tables) > 0:
rows = tables[0].xpath('./ss:Row', namespaces=namespaces)
for row in rows:
cells = row.xpath('./ss:Cell', namespaces=namespaces)
if len(cells) == 1: # skip if row have multiple 'cells'
if cells[0].attrib('./@ss:StyleID', namespaces=namespaces) == 'HeadTableTitle':
## execute some code ##
但是,当我执行代码的最后一行时,它会抛出 TypeError: 'lxml.etree._Attrib' object is not callable
要获取属性的值,您可以使用element.attrib['key']
或element.get('key')
。
在这两种情况下,如果属性绑定到命名空间,则您需要使用完整的命名空间 URI。
if cells[0].get('{urn:schemas-microsoft-com:office:spreadsheet}StyleID') == 'HeadTableTitle':