1 # -*- coding: utf-8 -*-
2 from librarian import ValidationError, NoDublinCore, dcparser, ParseError
3 from xml.parsers.expat import ExpatError
5 from lxml.etree import XMLSyntaxError
8 from StringIO import StringIO
10 class WLDocument(object):
11 LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
13 def __init__(self, edoc):
16 root_elem = edoc.getroot()
17 rdf_ns = dcparser.BookInfo.RDF
18 dc_path = './/' + rdf_ns('RDF')
20 if root_elem.tag != 'utwor':
21 raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
23 self.rdf_elem = root_elem.find(dc_path)
25 if self.rdf_elem is None:
26 raise NoDublinCore('Document has no DublinCore - which is required.')
28 self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
31 def from_string(cls, xml, swap_endlines=False):
32 return cls.from_file(StringIO(xml), swap_endlines)
35 def from_file(cls, xmlfile, swap_endlines=False):
37 # first, prepare for parsing
38 if isinstance(xmlfile, basestring):
39 file = open(xmlfile, 'rb')
47 if not isinstance(data, unicode):
48 data = data.decode('utf-8')
51 data = cls.LINE_SWAP_EXPR.sub(u'<br />\n', data)
54 parser = etree.XMLParser(remove_blank_text=True)
55 return cls( etree.parse(StringIO(data), parser) )
56 except XMLSyntaxError, e:
57 raise ParseError(e.message)
59 raise ParseError(e.message)
61 def transform(self, stylesheet, **options):
62 return self.edoc.xslt(stylesheet, **options)
65 parent = self.rdf_elem.getparent()
66 parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
70 return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)