我正在嘗試創建Element類的子類。儘管我開始有麻煩。難以創建lxml元素子類
from lxml import etree
try:
import docx
except ImportError:
from docx import docx
class File(etree.ElementBase):
def _init(self):
etree.ElementBase._init(self)
self.body = self.append(docx.makeelement('body'))
f = File()
relationships = docx.relationshiplist()
title = 'File'
subject = 'A very special File'
creator = 'Me'
keywords = ['python', 'Office Open XML', 'Word']
coreprops = docx.coreproperties(title=title, subject=subject, creator=creator,
keywords=keywords)
appprops = docx.appproperties()
contenttypes = docx.contenttypes()
websettings = docx.websettings()
wordrelationships = docx.wordrelationships(relationships)
docx.savedocx(f, coreprops, appprops, contenttypes, websettings,
wordrelationships, 'file.docx')
當我嘗試打開從該代碼輸出的文檔,我的(與兼容包2003)版本的Word使我有以下錯誤:「該文件是由Word 2007中的一個早期測試版本創建並且無法在此版本中打開。「當我用用docx.newdocument()創建的另一個元素替換File對象時,文檔顯示正常。任何想法/建議?
你的意思是你的構造函數使用'__init__'而不是'_init'嗎?此外,您可以嘗試檢查'docx.newdocument()'的[源代碼](https://github.com/mikemaccana/python-docx/blob/master/docx.py)以查看輸出應該是什麼樣子。它看起來像你缺少一個「文檔」標籤,儘管這只是我的猜測。 – Michael0x2a