Difficulty creating lxml Element subclass

不羁岁月 提交于 2019-12-11 18:02:15

问题


I’m trying to create a subclass of the Element class. I’m having trouble getting started though.

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')

When I try to open the document that is outputted from this code, my version of Word (2003 with compatibility pack) gives me the following error: “This file was created by a previous beta version of Word 2007 and cannot be opened in this version.” When I replace the File object with a different Element created with docx.newdocument(), the document comes out fine. Any ideas/advice?


回答1:


I don't really get why you want to use a separate class named File.

As Michael0x2a said, you did'nt put a document tag, so it won't work (I don't think Word 2007 can read your file too)

But here is the corrected code:

from lxml import etree
try:
    import docx
except ImportError:
    from docx import docx

class File(object):
    def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
                    attrnsprefix=None):
        '''Create an element & return it'''
        # Deal with list of nsprefix by making namespacemap
        namespacemap = None
        if isinstance(nsprefix, list):
            namespacemap = {}
            for prefix in nsprefix:
                namespacemap[prefix] = nsprefixes[prefix]
            # FIXME: rest of code below expects a single prefix
            nsprefix = nsprefix[0]
        if nsprefix:
            namespace = '{'+nsprefixes[nsprefix]+'}'
        else:
            # For when namespace = None
            namespace = ''
        newelement = etree.Element(namespace+tagname, nsmap=namespacemap)
        # Add attributes with namespaces
        if attributes:
            # If they haven't bothered setting attribute namespace, use an empty
            # string (equivalent of no namespace)
            if not attrnsprefix:
                # Quick hack: it seems every element that has a 'w' nsprefix for
                # its tag uses the same prefix for it's attributes
                if nsprefix == 'w':
                    attributenamespace = namespace
                else:
                    attributenamespace = ''
            else:
                attributenamespace = '{'+nsprefixes[attrnsprefix]+'}'

            for tagattribute in attributes:
                newelement.set(attributenamespace+tagattribute,
                               attributes[tagattribute])
        if tagtext:
            newelement.text = tagtext
        return newelement

    def __init__(self):
        super(File,self).__init__()
        self.document = self.makeelement('document')
        self.document.append(self.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.document, coreprops, appprops, contenttypes, websettings,
wordrelationships, 'file.docx')


来源:https://stackoverflow.com/questions/19096413/difficulty-creating-lxml-element-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!