595dd9791ca0c29485daa8490f5890ea11e66753
[librarian.git] / librarian / parser.py
1 # -*- coding: utf-8 -*-
2 from librarian import ValidationError, NoDublinCore, dcparser, ParseError
3 from xml.parsers.expat import ExpatError
4 from lxml import etree
5 from lxml.etree import XMLSyntaxError
6
7 import re
8 from StringIO import StringIO
9
10 class WLDocument(object):
11     LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
12
13     def __init__(self, edoc):
14         self.edoc = edoc
15
16         root_elem = edoc.getroot()
17         rdf_ns = dcparser.BookInfo.RDF
18         dc_path = './/' + rdf_ns('RDF')
19         
20         if root_elem.tag != 'utwor':
21             raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
22
23         self.rdf_elem = root_elem.find(dc_path)
24
25         if self.rdf_elem is None:
26             raise NoDublinCore('Document has no DublinCore - which is required.')
27
28         self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
29
30     @classmethod
31     def from_string(cls, xml, swap_endlines=False):
32         return cls.from_file(StringIO(xml), swap_endlines)
33
34     @classmethod
35     def from_file(cls, xmlfile, swap_endlines=False):
36
37         # first, prepare for parsing
38         if isinstance(xmlfile, basestring):
39             file = open(xmlfile, 'rb')
40             try:
41                 data = file.read()
42             finally:
43                 file.close()
44         else:
45             data = xmlfile.read()
46
47         if not isinstance(data, unicode):
48             data = data.decode('utf-8')
49
50         if swap_endlines:
51             data = cls.LINE_SWAP_EXPR.sub(u'<br />\n', data)
52     
53         try:
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)            
58         except ExpatError, e:
59             raise ParseError(e.message)            
60
61     def transform(self, stylesheet, **options):
62         return self.edoc.xslt(stylesheet, **options)
63
64     def update_dc(self):
65         parent = self.rdf_elem.getparent()
66         parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
67
68     def serialize(self):
69         self.update_dc()
70         return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)