import sys
from StringIO import StringIO
from xml.etree.ElementTree import Element, tostring
import xml.etree.ElementTree as etree
import xml.sax.handler
from xml.sax.handler import feature_namespaces
from asciitomathml import ascii_to_xml_string
from asciitomathml import ascii_to_math_tree
class CopyTree(xml.sax.ContentHandler):
"""
A simple class that copies a tree. Used for testing two xml strings.
"""
def __init__(self):
self.__characters = ''
self.__xml_string = ''
self.__default_ns = None
self.__mathml_ns = 'http://www.w3.org/1998/Math/MathML'
def characters (self, characters):
self.__characters += characters
def startElementNS(self, name, qname, attrs):
self.__write_text()
ns = name[0]
el_name = name[1]
root = None
self.__xml_string += '<'
if self.__default_ns == None:
if ns != self.__mathml_ns:
raise ValueError('wrong namespace "%s"' % (ns))
self.__default_ns = self.__mathml_ns
root = True
elif ns != self.__mathml_ns:
raise ValueError('wrong namespace')
self.__xml_string += el_name
if root:
self.__xml_string += ' xmlns="%s"' % ns
the_keys = attrs.keys()
the_keys.sort()
counter = 1
for the_key in the_keys:
counter +=1
ns_att = the_key[0]
att_name = the_key[1]
value = attrs[the_key]
if ns_att and ns_att != ns:
self.__xml_string += ' xmlns:ns%s="%s"' % (counter,ns_att)
if ns_att and ns_att == ns:
self.__xml_string += ' ns1:%s="%s"' % (att_name, value)
elif ns_att:
self.__xml_string += ' ns%s:%s="%s"' % (counter,att_name, value)
else:
self.__xml_string += ' %s="%s"' % (att_name, value)
self.__xml_string += '>'
def __write_text(self):
text = xml.sax.saxutils.escape(self.__characters)
# text = text.encode('utf8')
self.__xml_string += text
self.__characters = ''
def endElementNS(self, name, qname):
self.__write_text()
ns = name[0]
el_name = name[1]
self.__xml_string += '%s>' % el_name
def get_xml_string(self):
return self.__xml_string
def xml_copy_tree(xml_string, encoding='utf8'):
"""
Makes a simple copy of an XML string. Only used for testing purposes.
Two identical XML strings may have different syntax: