1 # -*- coding: utf-8 -*-
2 from librarian import ValidationError, NoDublinCore, ParseError
3 from librarian import RDFNS
4 from librarian import dcparser
6 from xml.parsers.expat import ExpatError
8 from lxml.etree import XMLSyntaxError, XSLTApplyError
11 from StringIO import StringIO
13 class WLDocument(object):
14 LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
16 def __init__(self, edoc, parse_dublincore=True):
19 root_elem = edoc.getroot()
21 dc_path = './/' + RDFNS('RDF')
23 if root_elem.tag != 'utwor':
24 raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
27 self.rdf_elem = root_elem.find(dc_path)
29 if self.rdf_elem is None:
30 raise NoDublinCore('Document has no DublinCore - which is required.')
32 self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
37 def from_string(cls, xml, swap_endlines=False, parse_dublincore=True):
38 return cls.from_file(StringIO(xml), swap_endlines, parse_dublincore=parse_dublincore)
41 def from_file(cls, xmlfile, swap_endlines=False, parse_dublincore=True):
43 # first, prepare for parsing
44 if isinstance(xmlfile, basestring):
45 file = open(xmlfile, 'rb')
53 if not isinstance(data, unicode):
54 data = data.decode('utf-8')
57 data = cls.LINE_SWAP_EXPR.sub(u'<br />\n', data)
60 parser = etree.XMLParser(remove_blank_text=False)
61 return cls(etree.parse(StringIO(data), parser), parse_dublincore=parse_dublincore)
62 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
65 def chunk(self, path):
66 # convert the path to XPath
67 expr = self.path_to_xpath(path)
68 elems = self.edoc.xpath(expr)
75 def path_to_xpath(self, path):
78 for part in path.split('/'):
79 match = re.match(r'([^\[]+)\[(\d+)\]', part)
83 tag, n = match.groups()
84 parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
89 return '/'.join(parts)
91 def transform(self, stylesheet, **options):
92 return self.edoc.xslt(stylesheet, **options)
96 parent = self.rdf_elem.getparent()
97 parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
101 return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)
103 def merge_chunks(self, chunk_dict):
106 for key, data in chunk_dict.iteritems():
108 xpath = self.path_to_xpath(key)
109 node = self.edoc.xpath(xpath)[0]
110 repl = etree.fromstring(u"<%s>%s</%s>" %(node.tag, data, node.tag) )
111 node.getparent().replace(node, repl);
113 unmerged.append( repr( (key, xpath, e) ) )