1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from StringIO import StringIO
9 from .core import Section
10 from .parser import SSTParser
13 class Document(object):
14 # Do I use meta_context?
15 def __init__(self, edoc, meta_context=None):
18 root_elem = edoc.getroot()
19 if meta_context is not None:
20 root_elem.meta_context = meta_context
22 if not isinstance(root_elem, Section):
23 if root_elem.tag != SSTNS('section'):
24 if root_elem.tag == 'section':
25 for element in root_elem.iter():
26 if element.tag in ('section', 'header', 'div', 'span', 'aside', 'metadata'):
27 element.tag = str(SSTNS(element.tag))
30 tree = etree.parse(StringIO(etree.tostring(root_elem)), parser)
34 raise ValueError("Invalid root element. Found '%s', should be '%s'" % (
35 root_elem.tag, SSTNS('section')))
37 raise ValueError("Invalid class of root element. "
38 "Use librarian.parser.SSTParser.")
39 #print etree.tostring(self.edoc.getroot())
42 def from_string(cls, xml, *args, **kwargs):
43 return cls.from_file(StringIO(xml), *args, **kwargs)
46 def from_file(cls, xmlfile, *args, **kwargs):
47 # first, prepare for parsing
48 if isinstance(xmlfile, basestring):
49 file = open(xmlfile, 'rb')
57 if not isinstance(data, unicode):
58 data = data.decode('utf-8')
60 data = data.replace(u'\ufeff', '')
61 # This is bad. The editor shouldn't spew unknown HTML entities.
62 data = data.replace(u' ', u'\u00a0')
65 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
67 return cls(tree, *args, **kwargs)
71 """ Document's metadata is root's metadata. """
72 return self.edoc.getroot().meta