如何在if语句中测试XML标记属性的值

2024-06-06 08:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

作为if语句的一部分,可以测试value标记属性的XML吗?你知道吗

例如,我有一个带有以下标记的XML

<Cell ss:StyleID="HeadTableTitle" ss:MergeAcross="1"><Data ss:Type="String">Administrative Data</Data></Cell>

我试图测试属性ss:StyleID==HeadTableTitle<Cell>标记中

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


Tags: path标记dataifcellschemasssxpath
1条回答
网友
1楼 · 发布于 2024-06-06 08:51:05

要获取属性的值,可以使用element.attrib['key']element.get('key')。你知道吗

在这两种情况下,如果属性绑定到命名空间,则需要使用完整的命名空间URI。你知道吗

if cells[0].get('{urn:schemas-microsoft-com:office:spreadsheet}StyleID') == 'HeadTableTitle':

相关问题 更多 >