【发布时间】:2017-06-16 17:17:36
【问题描述】:
我有一个 Excel XML 文件,我需要在其中获取具有确定颜色的单元格(内部)的元素的样式 ID。
我有这个 Excel xml,例如:
而且是文档的头部:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
这里是我需要访问的内容:
<Style ss:ID="s64">
<Interior ss:Color="#00CC00" ss:Pattern="Solid"/>
</Style>
我需要编写一个函数,传递颜色 #00CC00 我得到这个元素,然后我可以访问它的父元素来获取 ID。
我已尝试使用此代码,但它无效。我想我应该使用命名空间。
parser = et.parse(str(file))
color = parser.xpath("//interior[@ss:Color='#FFCC00'")
par = color.getparent()
print(par)
我需要代码返回“s64”。
但是它不是有效的代码。我错过了什么?
编辑:在寻找更多信息后,我想编辑我的问题并添加一些额外的信息,我已经编写了这段代码
def _find_color(self):
"""
Find the color in the xml file and returns the attribute.
"""
print('The folder is: ', self.path)
nsd ={'Default':'urn:schemas-microsoft-com:office:spreadsheet',
'o': 'urn:schemas-microsoft-com:office:office',
'ss': 'urn:schemas-microsoft-com:office:spreadsheet'}
if pathlib.Path(self.path).exists():
for file in self.folder.glob('**/*.xml'):
print('The file is ', file)
parser = et.parse(str(file))
color = parser.xpath("//style/interior[@ss:Color='#00CC00']",namespaces=nsd)
print(color)
#par = color.getparent()
#print(par)
但是它返回一个空列表。所以它什么也找不到。
添加我感兴趣的整个源代码部分
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>Somebody</Author>
<LastAuthor>Somebody</LastAuthor>
<Created>2016-05-16T10:44:52Z</Created>
<Company>SomeCompany</Company>
<Version>12.00</Version>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>9495</WindowHeight>
<WindowWidth>20835</WindowWidth>
<WindowTopX>240</WindowTopX>
<WindowTopY>420</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font ss:FontName="Arial" x:Family="Swiss"/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="s63">
<Font ss:FontName="Arial" x:Family="Swiss" ss:Color="#FF0000" ss:Bold="1"/>
</Style>
<Style ss:ID="s64">
<Interior ss:Color="#00CC00" ss:Pattern="Solid"/>
</Style>
<Style ss:ID="s65">
<Font ss:FontName="Arial" x:Family="Swiss" ss:Color="#FF0000" ss:Bold="1"/>
<Interior ss:Color="#44CF00" ss:Pattern="Solid"/>
</Style>
</Styles>
我无法使用 xpath 根据属性找到元素。
【问题讨论】:
标签: python python-3.x lxml