Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #137 from ionelmc/patch-2

Add CDATA support in ElementBuilder
  • Loading branch information...
commit b6eff208ebd3e28d0cdc60dc29cba60319c9b51c 2 parents 35316b0 + 14ce04b
@scoder scoder authored
Showing with 17 additions and 1 deletion.
  1. +9 −1 src/lxml/builder.py
  2. +8 −0 src/lxml/tests/test_builder.py
View
10 src/lxml/builder.py
@@ -177,16 +177,24 @@ def __init__(self, typemap=None,
typemap = typemap.copy()
else:
typemap = {}
-
+
def add_text(elem, item):
try:
elem[-1].tail = (elem[-1].tail or "") + item
except IndexError:
elem.text = (elem.text or "") + item
+
+ def add_cdata(elem, cdata):
+ if elem.text:
+ raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
+ elem.text = cdata
+
if str not in typemap:
typemap[str] = add_text
if unicode not in typemap:
typemap[unicode] = add_text
+ if ET.CDATA not in typemap:
+ typemap[ET.CDATA] = add_cdata
def add_dict(elem, item):
attrib = elem.attrib
View
8 src/lxml/tests/test_builder.py
@@ -15,6 +15,7 @@
from common_imports import HelperTestCase, BytesIO, _bytes
+
class BuilderTestCase(HelperTestCase):
etree = etree
@@ -28,6 +29,13 @@ class UnknownType(object):
pass
self.assertRaises(TypeError, E.b, UnknownType())
+ def test_cdata(self):
+ wrapped = E.b(etree.CDATA('Hello'))
+ self.assertEqual(_bytes('<b><![CDATA[Hello]]></b>'), etree.tostring(wrapped))
+
+ def test_cdata_solo(self):
+ self.assertRaises(ValueError, E.b, 'Hello', etree.CDATA('World'))
+
def test_suite():
suite = unittest.TestSuite()

0 comments on commit b6eff20

Please sign in to comment.
Something went wrong with that request. Please try again.