try:
    import lxml.etree as ET
except ImportError:
    import xml.etree.ElementTree as ET
from warnings import warn
from flattentool.exceptions import DataErrorWarning


def child_to_xml(parent_el, tagname, child):
    if hasattr(child, 'items'):
        child_el = dict_to_xml(child, tagname)
        if child_el is not None:
            parent_el.append(child_el)
    else:
        if tagname.startswith('@'):
            try:
                parent_el.attrib[tagname[1:]] = str(child)
            except ValueError as e:
                warn(str(e), DataErrorWarning)
        elif tagname == 'text()':
            parent_el.text = str(child)
        else:
            raise('Everything should end with text() or an attirbute!')


def dict_to_xml(data, tagname):
    try:
        el = ET.Element(tagname)
    except ValueError as e:
        warn(str(e), DataErrorWarning)
        return

    for k, v in data.items():
        if type(v) == list:
            for item in v:
                child_to_xml(el, k, item)
        else:
            child_to_xml(el, k, v)
    return el


def toxml(data):
    return ET.tostring(dict_to_xml(data, 'iati-activities'))

@@ -26,16 +26,38 @@
 e as ET%0A
+    USING_LXML = True%0A
 except I
@@ -107,16 +107,39 @@
 e as ET%0A
+    USING_LXML = False%0A
 from war
@@ -252,16 +252,44 @@
 e, child
+, toplevel=False, nsmap=None
 ):%0A    i
@@ -356,24 +356,53 @@
 ild, tagname
+, toplevel=False, nsmap=nsmap
 )%0A        if
@@ -517,28 +517,388 @@
             
-try:
+if USING_LXML and toplevel and tagname.startswith('@xmlns'):%0A                nsmap%5Btagname%5B1:%5D.split(':', 1)%5B1%5D%5D = str(child)%0A                return%0A            try:%0A                attr_name = tagname%5B1:%5D%0A                if USING_LXML and ':' in attr_name:%0A                    attr_name = '%7B' + nsmap%5Battr_name.split(':', 1)%5B0%5D%5D + '%7D' + attr_name.split(':', 1)%5B1%5D
 %0A           
@@ -919,27 +919,25 @@
 .attrib%5B
-tagname%5B1:%5D
+attr_name
 %5D = str(
@@ -1180,10 +1180,10 @@
  att
-i
 r
+i
 bute
@@ -1221,20 +1221,305 @@
 name
-):%0A    try:%0A
+, toplevel=True, nsmap=None):%0A    if USING_LXML and ':' in tagname and not toplevel:%0A        print(tagname)%0A        tagname = '%7B' + nsmap%5Btagname.split(':', 1)%5B0%5D%5D + '%7D' + tagname.split(':', 1)%5B1%5D%0A    try:%0A        if USING_LXML:%0A            el = ET.Element(tagname, nsmap=nsmap)%0A        else:%0A    
     
@@ -1755,16 +1755,29 @@
  k, item
+, nsmap=nsmap
 )%0A      
@@ -1817,16 +1817,48 @@
 el, k, v
+, toplevel=toplevel, nsmap=nsmap
 )%0A    re
@@ -1942,11 +1942,21 @@
 ivities'
+, nsmap=%7B%7D
 ))%0A

Support namespaces when using lxml