[英]LXML namespace in sub-elements formatted like XML spreadsheet
我在Python中使用LXML創建名稱空間時遇到麻煩。 我正在嘗試使用Python將特定數據從Excel轉換為XML電子表格格式。
我在下面創建了兩個子元素。 盡管我需要在ss:Name
之間使用:
,但第二個( WorksheetB
)幾乎是我需要生成的。 我的實驗行是第一個WorksheetA
。
我的目標是獲得一個看起來像這樣的XML標簽:
<WorksheetB ss:Name="This is worksheet B">
這是我的代碼:
namespaces = {
None:'urn:schemas-microsoft-com:office:spreadsheet',
'o':'urn:schemas-microsoft-com:office:office',
'x':'urn:schemas-microsoft-com:office:excel',
'ss':'urn:schemas-microsoft-com:office:spreadsheet',
'html':"http://www.w3.org/TR/REC-html40"
}
root = ET.Element('Workbook', nsmap = namespaces)
WorksheetA = ET.SubElement(root, '{%s}Name' % 'urn:schemas-microsoft-com:office:spreadsheet')
Table = ET.SubElement(WorksheetA, 'Table')
Row = ET.SubElement(Table, 'Row')
Cell = ET.SubElement(Row, 'Cell')
Data = ET.SubElement(Cell, 'Data')
Data.text = '1'
Cell = ET.SubElement(Row, 'Cell')
Data = ET.SubElement(Cell, 'Data')
Data.text = '2'
WorksheetB = ET.SubElement(root, 'WorksheetB', ssName="This is worksheet B")
Table = ET.SubElement(WorksheetB, 'Table')
Row = ET.SubElement(Table, 'Row')
Cell = ET.SubElement(Row, 'Cell')
Data = ET.SubElement(Cell, 'Data')
Data.text = '3'
Cell = ET.SubElement(Row, 'Cell')
Data = ET.SubElement(Cell, 'Data')
Data.text = '4'
tree = ET.ElementTree(root)
tree.write(TestXMLFile, pretty_print=True, xml_declaration=True)
這是輸出:
<?xml version='1.0' encoding='ASCII'?>
<Workbook xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns="urn:schemas-microsoft-com:office:spreadsheet">
<ss:Name>
<Table>
<Row>
<Cell>
<Data>1</Data>
</Cell>
<Cell>
<Data>2</Data>
</Cell>
</Row>
</Table>
</ss:Name>
<WorksheetB ssName="This is worksheet B">
<Table>
<Row>
<Cell>
<Data>3</Data>
</Cell>
<Cell>
<Data>4</Data>
</Cell>
</Row>
</Table>
</WorksheetB>
</Workbook>
如果您需要為Element
或SubElement
Element
的屬性使用名稱空間,則不能使用**kwargs
( **_extra
)語法傳遞名稱空間,因為這僅允許使用名稱有效的python標識符指定屬性。
因此,在這種情況下,您需要使用attrib
參數傳遞屬性,例如:
...
WorksheetB = ET.SubElement(root, 'WorksheetB',
{"{%s}Name" % namespaces['ss']: "This is worksheet B"})
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.