- parser = etree.XMLParser(remove_blank_text=True)
- return cls( etree.parse(StringIO(data), parser) )
- except XMLSyntaxError, e:
- raise ParseError(e.message)
- except ExpatError, e:
- raise ParseError(e.message)
+ parser = etree.XMLParser(remove_blank_text=False)
+ tree = etree.parse(StringIO(data.encode('utf-8')), parser)
+
+ if swap_endlines:
+ cls.swap_endlines(tree)
+
+ return cls(tree, parse_dublincore=parse_dublincore)
+ except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
+ raise ParseError(e)
+
+ @classmethod
+ def swap_endlines(cls, tree):
+ # only swap inside stanzas
+ for elem in tree.iter('strofa'):
+ for child in list(elem):
+ if child.tail:
+ chunks = cls.LINE_SWAP_EXPR.split(child.tail)
+ ins_index = elem.index(child) + 1
+ while len(chunks) > 1:
+ ins = etree.Element('br')
+ ins.tail = chunks.pop()
+ elem.insert(ins_index, ins)
+ child.tail = chunks.pop(0)
+ if elem.text:
+ chunks = cls.LINE_SWAP_EXPR.split(elem.text)
+ while len(chunks) > 1:
+ ins = etree.Element('br')
+ ins.tail = chunks.pop()
+ elem.insert(0, ins)
+ elem.text = chunks.pop(0)
+
+ def chunk(self, path):
+ # convert the path to XPath
+ expr = self.path_to_xpath(path)
+ elems = self.edoc.xpath(expr)
+
+ if len(elems) == 0:
+ return None
+ else:
+ return elems[0]
+
+ def path_to_xpath(self, path):
+ parts = []
+
+ for part in path.split('/'):
+ match = re.match(r'([^\[]+)\[(\d+)\]', part)
+ if not match:
+ parts.append(part)
+ else:
+ tag, n = match.groups()
+ parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
+
+ if parts[0] == '.':
+ parts[0] = ''
+
+ return '/'.join(parts)