Back to index

python3.2  3.2.2
Classes | Functions | Variables
test.test_xml_etree Namespace Reference

Classes

class  ExceptionFile
class  CleanContext

Functions

def sanity
def check_method
def serialize
def summarize
def summarize_list
def normalize_crlf
def normalize_exception
def check_string
def check_mapping
def check_element
def interface
def simpleops
def cdata
def simplefind
def find
def file_init
def bad_find
def path_cache
def copy
def attrib
def makeelement
def parsefile
def parseliteral
def iterparse
def writefile
def custom_builder
def getchildren
def writestring
def check_encoding
def encoding
def methods
def iterators
def entity
def error
def namespace
def qname
def doctype_public
def xpath_tokenizer
def processinginstruction
def xinclude_loader
def xinclude
def xinclude_default
def xinclude_failures
def bug_xmltoolkit21
def bug_xmltoolkit25
def bug_xmltoolkit28
def bug_xmltoolkitX1
def bug_xmltoolkit39
def bug_xmltoolkit54
def bug_xmltoolkit55
def xmltoolkit60
def xmltoolkit62
def xmltoolkit63
def bug_200708_newline
def bug_200708_close
def bug_200709_default_namespace
def bug_200709_register_namespace
def bug_200709_element_comment
def bug_200709_element_insert
def bug_200709_iter_comment
def bug_1534630
def check_issue6233
def check_issue3151
def check_issue6565
def check_issue10777
def test_main

Variables

tuple SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata")
tuple SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata")
string SAMPLE_XML
string SAMPLE_SECTION
string SAMPLE_XML_NS
string ENTITY_XML
dictionary XINCLUDE = {}
dictionary XINCLUDE_BAD = {}
string XMLTOOLKIT62_DOC

Function Documentation

Test attribute handling.

>>> elem = ET.Element("tag")
>>> elem.get("key") # 1.1
>>> elem.get("key", "default") # 1.2
'default'
>>> elem.set("key", "value")
>>> elem.get("key") # 1.3
'value'

>>> elem = ET.Element("tag", key="value")
>>> elem.get("key") # 2.1
'value'
>>> elem.attrib # 2.2
{'key': 'value'}

>>> attrib = {"key": "value"}
>>> elem = ET.Element("tag", attrib)
>>> attrib.clear() # check for aliasing issues
>>> elem.get("key") # 3.1
'value'
>>> elem.attrib # 3.2
{'key': 'value'}

>>> attrib = {"key": "value"}
>>> elem = ET.Element("tag", **attrib)
>>> attrib.clear() # check for aliasing issues
>>> elem.get("key") # 4.1
'value'
>>> elem.attrib # 4.2
{'key': 'value'}

>>> elem = ET.Element("tag", {"key": "other"}, key="value")
>>> elem.get("key") # 5.1
'value'
>>> elem.attrib # 5.2
{'key': 'value'}

>>> elem = ET.Element('test')
>>> elem.text = "aa"
>>> elem.set('testa', 'testval')
>>> elem.set('testb', 'test2')
>>> ET.tostring(elem)
b'<test testa="testval" testb="test2">aa</test>'
>>> sorted(elem.keys())
['testa', 'testb']
>>> sorted(elem.items())
[('testa', 'testval'), ('testb', 'test2')]
>>> elem.attrib['testb']
'test2'
>>> elem.attrib['testb'] = 'test1'
>>> elem.attrib['testc'] = 'test2'
>>> ET.tostring(elem)
b'<test testa="testval" testb="test1" testc="test2">aa</test>'

Definition at line 495 of file test_xml_etree.py.

00495 
00496 def attrib():
00497     """
00498     Test attribute handling.
00499 
00500     >>> elem = ET.Element("tag")
00501     >>> elem.get("key") # 1.1
00502     >>> elem.get("key", "default") # 1.2
00503     'default'
00504     >>> elem.set("key", "value")
00505     >>> elem.get("key") # 1.3
00506     'value'
00507 
00508     >>> elem = ET.Element("tag", key="value")
00509     >>> elem.get("key") # 2.1
00510     'value'
00511     >>> elem.attrib # 2.2
00512     {'key': 'value'}
00513 
00514     >>> attrib = {"key": "value"}
00515     >>> elem = ET.Element("tag", attrib)
00516     >>> attrib.clear() # check for aliasing issues
00517     >>> elem.get("key") # 3.1
00518     'value'
00519     >>> elem.attrib # 3.2
00520     {'key': 'value'}
00521 
00522     >>> attrib = {"key": "value"}
00523     >>> elem = ET.Element("tag", **attrib)
00524     >>> attrib.clear() # check for aliasing issues
00525     >>> elem.get("key") # 4.1
00526     'value'
00527     >>> elem.attrib # 4.2
00528     {'key': 'value'}
00529 
00530     >>> elem = ET.Element("tag", {"key": "other"}, key="value")
00531     >>> elem.get("key") # 5.1
00532     'value'
00533     >>> elem.attrib # 5.2
00534     {'key': 'value'}
00535 
00536     >>> elem = ET.Element('test')
00537     >>> elem.text = "aa"
00538     >>> elem.set('testa', 'testval')
00539     >>> elem.set('testb', 'test2')
00540     >>> ET.tostring(elem)
00541     b'<test testa="testval" testb="test2">aa</test>'
00542     >>> sorted(elem.keys())
00543     ['testa', 'testb']
00544     >>> sorted(elem.items())
00545     [('testa', 'testval'), ('testb', 'test2')]
00546     >>> elem.attrib['testb']
00547     'test2'
00548     >>> elem.attrib['testb'] = 'test1'
00549     >>> elem.attrib['testc'] = 'test2'
00550     >>> ET.tostring(elem)
00551     b'<test testa="testval" testb="test1" testc="test2">aa</test>'
00552     """

Here is the caller graph for this function:

Check bad or unsupported path expressions.

>>> elem = ET.XML(SAMPLE_XML)
>>> elem.findall("/tag")
Traceback (most recent call last):
SyntaxError: cannot use absolute path on element

Definition at line 449 of file test_xml_etree.py.

00449 
00450 def bad_find():
00451     """
00452     Check bad or unsupported path expressions.
00453 
00454     >>> elem = ET.XML(SAMPLE_XML)
00455     >>> elem.findall("/tag")
00456     Traceback (most recent call last):
00457     SyntaxError: cannot use absolute path on element
00458     """

>>> bob = ET.TreeBuilder()
>>> e = bob.data("data")
>>> e = bob.start("tag", {})
>>> e = bob.end("tag")
>>> e = bob.close()
>>> serialize(e)
'<tag />'

Definition at line 1794 of file test_xml_etree.py.

01794 
01795 def bug_1534630():
01796     """
01797 
01798     >>> bob = ET.TreeBuilder()
01799     >>> e = bob.data("data")
01800     >>> e = bob.start("tag", {})
01801     >>> e = bob.end("tag")
01802     >>> e = bob.close()
01803     >>> serialize(e)
01804     '<tag />'
01805 
01806     """

Test default builder.
>>> parser = ET.XMLParser() # default
>>> parser.feed("<element>some text</element>")
>>> summarize(parser.close())
'element'

Test custom builder.
>>> class EchoTarget:
...     def close(self):
...         return ET.Element("element") # simulate root
>>> parser = ET.XMLParser(EchoTarget())
>>> parser.feed("<element>some text</element>")
>>> summarize(parser.close())
'element'

Definition at line 1686 of file test_xml_etree.py.

01686 
01687 def bug_200708_close():
01688     """
01689 
01690     Test default builder.
01691     >>> parser = ET.XMLParser() # default
01692     >>> parser.feed("<element>some text</element>")
01693     >>> summarize(parser.close())
01694     'element'
01695 
01696     Test custom builder.
01697     >>> class EchoTarget:
01698     ...     def close(self):
01699     ...         return ET.Element("element") # simulate root
01700     >>> parser = ET.XMLParser(EchoTarget())
01701     >>> parser.feed("<element>some text</element>")
01702     >>> summarize(parser.close())
01703     'element'
01704 
01705     """

Definition at line 1671 of file test_xml_etree.py.

01671 
01672 def bug_200708_newline():
01673     r"""
01674 
01675     Preserve newlines in attributes.
01676 
01677     >>> e = ET.Element('SomeTag', text="def _f():\n  return 3\n")
01678     >>> ET.tostring(e)
01679     b'<SomeTag text="def _f():&#10;  return 3&#10;" />'
01680     >>> ET.XML(ET.tostring(e)).get("text")
01681     'def _f():\n  return 3\n'
01682     >>> ET.tostring(ET.XML(ET.tostring(e)))
01683     b'<SomeTag text="def _f():&#10;  return 3&#10;" />'
01684 
01685     """

>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e, "{default}elem")
>>> serialize(e, default_namespace="default") # 1
'<elem xmlns="default"><elem /></elem>'

>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e, "{default}elem")
>>> s = ET.SubElement(e, "{not-default}elem")
>>> serialize(e, default_namespace="default") # 2
'<elem xmlns="default" xmlns:ns1="not-default"><elem /><ns1:elem /></elem>'

>>> e = ET.Element("{default}elem")
>>> s = ET.SubElement(e, "{default}elem")
>>> s = ET.SubElement(e, "elem") # unprefixed name
>>> serialize(e, default_namespace="default") # 3
Traceback (most recent call last):
ValueError: cannot use non-qualified names with default_namespace option

Definition at line 1706 of file test_xml_etree.py.

01706 
01707 def bug_200709_default_namespace():
01708     """
01709 
01710     >>> e = ET.Element("{default}elem")
01711     >>> s = ET.SubElement(e, "{default}elem")
01712     >>> serialize(e, default_namespace="default") # 1
01713     '<elem xmlns="default"><elem /></elem>'
01714 
01715     >>> e = ET.Element("{default}elem")
01716     >>> s = ET.SubElement(e, "{default}elem")
01717     >>> s = ET.SubElement(e, "{not-default}elem")
01718     >>> serialize(e, default_namespace="default") # 2
01719     '<elem xmlns="default" xmlns:ns1="not-default"><elem /><ns1:elem /></elem>'
01720 
01721     >>> e = ET.Element("{default}elem")
01722     >>> s = ET.SubElement(e, "{default}elem")
01723     >>> s = ET.SubElement(e, "elem") # unprefixed name
01724     >>> serialize(e, default_namespace="default") # 3
01725     Traceback (most recent call last):
01726     ValueError: cannot use non-qualified names with default_namespace option
01727 
01728     """

Not sure if this can be fixed, really (since the serializer needs
ET.Comment, not cET.comment).

>>> a = ET.Element('a')
>>> a.append(ET.Comment('foo'))
>>> a[0].tag == ET.Comment
True

>>> a = ET.Element('a')
>>> a.append(ET.PI('foo'))
>>> a[0].tag == ET.PI
True

Definition at line 1745 of file test_xml_etree.py.

01745 
01746 def bug_200709_element_comment():
01747     """
01748 
01749     Not sure if this can be fixed, really (since the serializer needs
01750     ET.Comment, not cET.comment).
01751 
01752     >>> a = ET.Element('a')
01753     >>> a.append(ET.Comment('foo'))
01754     >>> a[0].tag == ET.Comment
01755     True
01756 
01757     >>> a = ET.Element('a')
01758     >>> a.append(ET.PI('foo'))
01759     >>> a[0].tag == ET.PI
01760     True
01761 
01762     """

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.Element('d')
>>> a.insert(0, d)
>>> summarize_list(a)
['d', 'b', 'c']
>>> a.insert(-1, d)
>>> summarize_list(a)
['d', 'b', 'd', 'c']

Definition at line 1763 of file test_xml_etree.py.

01763 
01764 def bug_200709_element_insert():
01765     """
01766 
01767     >>> a = ET.Element('a')
01768     >>> b = ET.SubElement(a, 'b')
01769     >>> c = ET.SubElement(a, 'c')
01770     >>> d = ET.Element('d')
01771     >>> a.insert(0, d)
01772     >>> summarize_list(a)
01773     ['d', 'b', 'c']
01774     >>> a.insert(-1, d)
01775     >>> summarize_list(a)
01776     ['d', 'b', 'd', 'c']
01777 
01778     """

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> comment_b = ET.Comment("TEST-b")
>>> b.append(comment_b)
>>> summarize_list(a.iter(ET.Comment))
['<Comment>']

Definition at line 1779 of file test_xml_etree.py.

01779 
01780 def bug_200709_iter_comment():
01781     """
01782 
01783     >>> a = ET.Element('a')
01784     >>> b = ET.SubElement(a, 'b')
01785     >>> comment_b = ET.Comment("TEST-b")
01786     >>> b.append(comment_b)
01787     >>> summarize_list(a.iter(ET.Comment))
01788     ['<Comment>']
01789 
01790     """
01791 
01792 # --------------------------------------------------------------------
01793 # reported on bugs.python.org

>>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />'
>>> ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/")
>>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />'

And the Dublin Core namespace is in the default list:

>>> ET.tostring(ET.Element("{http://purl.org/dc/elements/1.1/}title"))
b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />'

Definition at line 1729 of file test_xml_etree.py.

01729 
01730 def bug_200709_register_namespace():
01731     """
01732 
01733     >>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
01734     b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />'
01735     >>> ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/")
01736     >>> ET.tostring(ET.Element("{http://namespace.invalid/does/not/exist/}title"))
01737     b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />'
01738 
01739     And the Dublin Core namespace is in the default list:
01740 
01741     >>> ET.tostring(ET.Element("{http://purl.org/dc/elements/1.1/}title"))
01742     b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />'
01743 
01744     """

marshaller gives obscure errors for non-string values

>>> elem = ET.Element(123)
>>> serialize(elem) # tag
Traceback (most recent call last):
TypeError: cannot serialize 123 (type int)
>>> elem = ET.Element("elem")
>>> elem.text = 123
>>> serialize(elem) # text
Traceback (most recent call last):
TypeError: cannot serialize 123 (type int)
>>> elem = ET.Element("elem")
>>> elem.tail = 123
>>> serialize(elem) # tail
Traceback (most recent call last):
TypeError: cannot serialize 123 (type int)
>>> elem = ET.Element("elem")
>>> elem.set(123, "123")
>>> serialize(elem) # attribute key
Traceback (most recent call last):
TypeError: cannot serialize 123 (type int)
>>> elem = ET.Element("elem")
>>> elem.set("123", 123)
>>> serialize(elem) # attribute value
Traceback (most recent call last):
TypeError: cannot serialize 123 (type int)

Definition at line 1487 of file test_xml_etree.py.

01487 
01488 def bug_xmltoolkit21():
01489     """
01490 
01491     marshaller gives obscure errors for non-string values
01492 
01493     >>> elem = ET.Element(123)
01494     >>> serialize(elem) # tag
01495     Traceback (most recent call last):
01496     TypeError: cannot serialize 123 (type int)
01497     >>> elem = ET.Element("elem")
01498     >>> elem.text = 123
01499     >>> serialize(elem) # text
01500     Traceback (most recent call last):
01501     TypeError: cannot serialize 123 (type int)
01502     >>> elem = ET.Element("elem")
01503     >>> elem.tail = 123
01504     >>> serialize(elem) # tail
01505     Traceback (most recent call last):
01506     TypeError: cannot serialize 123 (type int)
01507     >>> elem = ET.Element("elem")
01508     >>> elem.set(123, "123")
01509     >>> serialize(elem) # attribute key
01510     Traceback (most recent call last):
01511     TypeError: cannot serialize 123 (type int)
01512     >>> elem = ET.Element("elem")
01513     >>> elem.set("123", 123)
01514     >>> serialize(elem) # attribute value
01515     Traceback (most recent call last):
01516     TypeError: cannot serialize 123 (type int)
01517 
01518     """

typo in ElementTree.findtext

>>> elem = ET.XML(SAMPLE_XML)
>>> tree = ET.ElementTree(elem)
>>> tree.findtext("tag")
'text'
>>> tree.findtext("section/tag")
'subtext'

Definition at line 1519 of file test_xml_etree.py.

01519 
01520 def bug_xmltoolkit25():
01521     """
01522 
01523     typo in ElementTree.findtext
01524 
01525     >>> elem = ET.XML(SAMPLE_XML)
01526     >>> tree = ET.ElementTree(elem)
01527     >>> tree.findtext("tag")
01528     'text'
01529     >>> tree.findtext("section/tag")
01530     'subtext'
01531 
01532     """

.//tag causes exceptions

>>> tree = ET.XML("<doc><table><tbody/></table></doc>")
>>> summarize_list(tree.findall(".//thead"))
[]
>>> summarize_list(tree.findall(".//tbody"))
['tbody']

Definition at line 1533 of file test_xml_etree.py.

01533 
01534 def bug_xmltoolkit28():
01535     """
01536 
01537     .//tag causes exceptions
01538 
01539     >>> tree = ET.XML("<doc><table><tbody/></table></doc>")
01540     >>> summarize_list(tree.findall(".//thead"))
01541     []
01542     >>> summarize_list(tree.findall(".//tbody"))
01543     ['tbody']
01544 
01545     """

non-ascii element and attribute names doesn't work

>>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\\xe4g />")
>>> ET.tostring(tree, "utf-8")
b'<t\\xc3\\xa4g />'

>>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><tag \\xe4ttr='v&#228;lue' />")
>>> tree.attrib
{'\\xe4ttr': 'v\\xe4lue'}
>>> ET.tostring(tree, "utf-8")
b'<tag \\xc3\\xa4ttr="v\\xc3\\xa4lue" />'

>>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\\xe4g>text</t\\xe4g>")
>>> ET.tostring(tree, "utf-8")
b'<t\\xc3\\xa4g>text</t\\xc3\\xa4g>'

>>> tree = ET.Element("t\u00e4g")
>>> ET.tostring(tree, "utf-8")
b'<t\\xc3\\xa4g />'

>>> tree = ET.Element("tag")
>>> tree.set("\u00e4ttr", "v\u00e4lue")
>>> ET.tostring(tree, "utf-8")
b'<tag \\xc3\\xa4ttr="v\\xc3\\xa4lue" />'

Definition at line 1558 of file test_xml_etree.py.

01558 
01559 def bug_xmltoolkit39():
01560     """
01561 
01562     non-ascii element and attribute names doesn't work
01563 
01564     >>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\\xe4g />")
01565     >>> ET.tostring(tree, "utf-8")
01566     b'<t\\xc3\\xa4g />'
01567 
01568     >>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><tag \\xe4ttr='v&#228;lue' />")
01569     >>> tree.attrib
01570     {'\\xe4ttr': 'v\\xe4lue'}
01571     >>> ET.tostring(tree, "utf-8")
01572     b'<tag \\xc3\\xa4ttr="v\\xc3\\xa4lue" />'
01573 
01574     >>> tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\\xe4g>text</t\\xe4g>")
01575     >>> ET.tostring(tree, "utf-8")
01576     b'<t\\xc3\\xa4g>text</t\\xc3\\xa4g>'
01577 
01578     >>> tree = ET.Element("t\u00e4g")
01579     >>> ET.tostring(tree, "utf-8")
01580     b'<t\\xc3\\xa4g />'
01581 
01582     >>> tree = ET.Element("tag")
01583     >>> tree.set("\u00e4ttr", "v\u00e4lue")
01584     >>> ET.tostring(tree, "utf-8")
01585     b'<tag \\xc3\\xa4ttr="v\\xc3\\xa4lue" />'
01586 
01587     """

problems handling internally defined entities

>>> e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]><doc>&ldots;</doc>")
>>> serialize(e, encoding="us-ascii")
b'<doc>&#33328;</doc>'
>>> serialize(e)
'<doc>\u8230</doc>'

Definition at line 1588 of file test_xml_etree.py.

01588 
01589 def bug_xmltoolkit54():
01590     """
01591 
01592     problems handling internally defined entities
01593 
01594     >>> e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]><doc>&ldots;</doc>")
01595     >>> serialize(e, encoding="us-ascii")
01596     b'<doc>&#33328;</doc>'
01597     >>> serialize(e)
01598     '<doc>\u8230</doc>'
01599 
01600     """

make sure we're reporting the first error, not the last

>>> normalize_exception(ET.XML, b"<!DOCTYPE doc SYSTEM 'doc.dtd'><doc>&ldots;&ndots;&rdots;</doc>")
Traceback (most recent call last):
ParseError: undefined entity &ldots;: line 1, column 36

Definition at line 1601 of file test_xml_etree.py.

01601 
01602 def bug_xmltoolkit55():
01603     """
01604 
01605     make sure we're reporting the first error, not the last
01606 
01607     >>> normalize_exception(ET.XML, b"<!DOCTYPE doc SYSTEM 'doc.dtd'><doc>&ldots;&ndots;&rdots;</doc>")
01608     Traceback (most recent call last):
01609     ParseError: undefined entity &ldots;: line 1, column 36
01610 
01611     """

dump() doesn't flush the output buffer

>>> tree = ET.XML("<doc><table><tbody/></table></doc>")
>>> ET.dump(tree); print("tail")
<doc><table><tbody /></table></doc>
tail

Definition at line 1546 of file test_xml_etree.py.

01546 
01547 def bug_xmltoolkitX1():
01548     """
01549 
01550     dump() doesn't flush the output buffer
01551 
01552     >>> tree = ET.XML("<doc><table><tbody/></table></doc>")
01553     >>> ET.dump(tree); print("tail")
01554     <doc><table><tbody /></table></doc>
01555     tail
01556 
01557     """

Test CDATA handling (etc).

>>> serialize(ET.XML("<tag>hello</tag>"))
'<tag>hello</tag>'
>>> serialize(ET.XML("<tag>&#104;&#101;&#108;&#108;&#111;</tag>"))
'<tag>hello</tag>'
>>> serialize(ET.XML("<tag><![CDATA[hello]]></tag>"))
'<tag>hello</tag>'

Definition at line 261 of file test_xml_etree.py.

00261 
00262 def cdata():
00263     """
00264     Test CDATA handling (etc).
00265 
00266     >>> serialize(ET.XML("<tag>hello</tag>"))
00267     '<tag>hello</tag>'
00268     >>> serialize(ET.XML("<tag>&#104;&#101;&#108;&#108;&#111;</tag>"))
00269     '<tag>hello</tag>'
00270     >>> serialize(ET.XML("<tag><![CDATA[hello]]></tag>"))
00271     '<tag>hello</tag>'
00272     """
00273 
# Only with Python implementation

Definition at line 130 of file test_xml_etree.py.

00130 
00131 def check_element(element):
00132     if not ET.iselement(element):
00133         print("not an element")
00134     if not hasattr(element, "tag"):
00135         print("no tag member")
00136     if not hasattr(element, "attrib"):
00137         print("no attrib member")
00138     if not hasattr(element, "text"):
00139         print("no text member")
00140     if not hasattr(element, "tail"):
00141         print("no tail member")
00142 
00143     check_string(element.tag)
00144     check_mapping(element.attrib)
00145     if element.text is not None:
00146         check_string(element.text)
00147     if element.tail is not None:
00148         check_string(element.tail)
00149     for elem in element:
00150         check_element(elem)
00151 
00152 # --------------------------------------------------------------------
00153 # element tree tests

Here is the call graph for this function:

>>> check_encoding("ascii")
>>> check_encoding("us-ascii")
>>> check_encoding("iso-8859-1")
>>> check_encoding("iso-8859-15")
>>> check_encoding("cp437")
>>> check_encoding("mac-roman")

Definition at line 893 of file test_xml_etree.py.

00893 
00894 def check_encoding(encoding):
00895     """
00896     >>> check_encoding("ascii")
00897     >>> check_encoding("us-ascii")
00898     >>> check_encoding("iso-8859-1")
00899     >>> check_encoding("iso-8859-15")
00900     >>> check_encoding("cp437")
00901     >>> check_encoding("mac-roman")
00902     """
00903     ET.XML("<?xml version='1.0' encoding='%s'?><xml />" % encoding)

Registering a namespace twice caused a "dictionary changed size during
iteration" bug.

>>> ET.register_namespace('test10777', 'http://myuri/')
>>> ET.register_namespace('test10777', 'http://myuri/')

Definition at line 1844 of file test_xml_etree.py.

01844 
01845 def check_issue10777():
01846     """
01847     Registering a namespace twice caused a "dictionary changed size during
01848     iteration" bug.
01849 
01850     >>> ET.register_namespace('test10777', 'http://myuri/')
01851     >>> ET.register_namespace('test10777', 'http://myuri/')
01852     """
01853 
01854 # --------------------------------------------------------------------
01855 

>>> e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>')
>>> e.tag
'{${stuff}}localname'
>>> t = ET.ElementTree(e)
>>> ET.tostring(e)
b'<ns0:localname xmlns:ns0="${stuff}" />'

Definition at line 1819 of file test_xml_etree.py.

01819 
01820 def check_issue3151():
01821     """
01822 
01823     >>> e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>')
01824     >>> e.tag
01825     '{${stuff}}localname'
01826     >>> t = ET.ElementTree(e)
01827     >>> ET.tostring(e)
01828     b'<ns0:localname xmlns:ns0="${stuff}" />'
01829 
01830     """

>>> e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?><body>t\\xc3\\xa3g</body>")
>>> ET.tostring(e, 'ascii')
b"<?xml version='1.0' encoding='ascii'?>\\n<body>t&#227;g</body>"
>>> e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><body>t\\xe3g</body>")
>>> ET.tostring(e, 'ascii')
b"<?xml version='1.0' encoding='ascii'?>\\n<body>t&#227;g</body>"

Definition at line 1807 of file test_xml_etree.py.

01807 
01808 def check_issue6233():
01809     """
01810 
01811     >>> e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?><body>t\\xc3\\xa3g</body>")
01812     >>> ET.tostring(e, 'ascii')
01813     b"<?xml version='1.0' encoding='ascii'?>\\n<body>t&#227;g</body>"
01814     >>> e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><body>t\\xe3g</body>")
01815     >>> ET.tostring(e, 'ascii')
01816     b"<?xml version='1.0' encoding='ascii'?>\\n<body>t&#227;g</body>"
01817 
01818     """

>>> elem = ET.XML("<body><tag/></body>")
>>> summarize_list(elem)
['tag']
>>> newelem = ET.XML(SAMPLE_XML)
>>> elem[:] = newelem[:]
>>> summarize_list(elem)
['tag', 'tag', 'section']

Definition at line 1831 of file test_xml_etree.py.

01831 
01832 def check_issue6565():
01833     """
01834 
01835     >>> elem = ET.XML("<body><tag/></body>")
01836     >>> summarize_list(elem)
01837     ['tag']
01838     >>> newelem = ET.XML(SAMPLE_XML)
01839     >>> elem[:] = newelem[:]
01840     >>> summarize_list(elem)
01841     ['tag', 'tag', 'section']
01842 
01843     """

Definition at line 120 of file test_xml_etree.py.

00120 
00121 def check_mapping(mapping):
00122     len(mapping)
00123     keys = mapping.keys()
00124     items = mapping.items()
00125     for key in keys:
00126         item = mapping[key]
00127     mapping["key"] = "value"
00128     if mapping["key"] != "value":
00129         print("expected value string, got %r" % mapping["key"])

Here is the caller graph for this function:

Definition at line 70 of file test_xml_etree.py.

00070 
00071 def check_method(method):
00072     if not hasattr(method, '__call__'):
00073         print(method, "not callable")

Definition at line 111 of file test_xml_etree.py.

00111 
00112 def check_string(string):
00113     len(string)
00114     for char in string:
00115         if len(char) != 1:
00116             print("expected one-character string, got %r" % char)
00117     new_string = string + ""
00118     new_string = string + " "
00119     string[:0]

Here is the caller graph for this function:

Test copy handling (etc).

>>> import copy
>>> e1 = ET.XML("<tag>hello<foo/></tag>")
>>> e2 = copy.copy(e1)
>>> e3 = copy.deepcopy(e1)
>>> e1.find("foo").tag = "bar"
>>> serialize(e1)
'<tag>hello<bar /></tag>'
>>> serialize(e2)
'<tag>hello<bar /></tag>'
>>> serialize(e3)
'<tag>hello<foo /></tag>'

Definition at line 477 of file test_xml_etree.py.

00477 
00478 def copy():
00479     """
00480     Test copy handling (etc).
00481 
00482     >>> import copy
00483     >>> e1 = ET.XML("<tag>hello<foo/></tag>")
00484     >>> e2 = copy.copy(e1)
00485     >>> e3 = copy.deepcopy(e1)
00486     >>> e1.find("foo").tag = "bar"
00487     >>> serialize(e1)
00488     '<tag>hello<bar /></tag>'
00489     >>> serialize(e2)
00490     '<tag>hello<bar /></tag>'
00491     >>> serialize(e3)
00492     '<tag>hello<foo /></tag>'
00493 
00494     """

Test parser w. custom builder.

>>> with open(SIMPLE_XMLFILE) as f:
...     data = f.read()
>>> class Builder:
...     def start(self, tag, attrib):
...         print("start", tag)
...     def end(self, tag):
...         print("end", tag)
...     def data(self, text):
...         pass
>>> builder = Builder()
>>> parser = ET.XMLParser(target=builder)
>>> parser.feed(data)
start root
start element
end element
start element
end element
start empty-element
end empty-element
end root

>>> with open(SIMPLE_NS_XMLFILE) as f:
...     data = f.read()
>>> class Builder:
...     def start(self, tag, attrib):
...         print("start", tag)
...     def end(self, tag):
...         print("end", tag)
...     def data(self, text):
...         pass
...     def pi(self, target, data):
...         print("pi", target, repr(data))
...     def comment(self, data):
...         print("comment", repr(data))
>>> builder = Builder()
>>> parser = ET.XMLParser(target=builder)
>>> parser.feed(data)
pi pi 'data'
comment ' comment '
start {namespace}root
start {namespace}element
end {namespace}element
start {namespace}element
end {namespace}element
start {namespace}empty-element
end {namespace}empty-element
end {namespace}root

Definition at line 782 of file test_xml_etree.py.

00782 
00783 def custom_builder():
00784     """
00785     Test parser w. custom builder.
00786 
00787     >>> with open(SIMPLE_XMLFILE) as f:
00788     ...     data = f.read()
00789     >>> class Builder:
00790     ...     def start(self, tag, attrib):
00791     ...         print("start", tag)
00792     ...     def end(self, tag):
00793     ...         print("end", tag)
00794     ...     def data(self, text):
00795     ...         pass
00796     >>> builder = Builder()
00797     >>> parser = ET.XMLParser(target=builder)
00798     >>> parser.feed(data)
00799     start root
00800     start element
00801     end element
00802     start element
00803     end element
00804     start empty-element
00805     end empty-element
00806     end root
00807 
00808     >>> with open(SIMPLE_NS_XMLFILE) as f:
00809     ...     data = f.read()
00810     >>> class Builder:
00811     ...     def start(self, tag, attrib):
00812     ...         print("start", tag)
00813     ...     def end(self, tag):
00814     ...         print("end", tag)
00815     ...     def data(self, text):
00816     ...         pass
00817     ...     def pi(self, target, data):
00818     ...         print("pi", target, repr(data))
00819     ...     def comment(self, data):
00820     ...         print("comment", repr(data))
00821     >>> builder = Builder()
00822     >>> parser = ET.XMLParser(target=builder)
00823     >>> parser.feed(data)
00824     pi pi 'data'
00825     comment ' comment '
00826     start {namespace}root
00827     start {namespace}element
00828     end {namespace}element
00829     start {namespace}element
00830     end {namespace}element
00831     start {namespace}empty-element
00832     end {namespace}empty-element
00833     end {namespace}root
00834 
00835     """

Test PUBLIC doctype.

>>> elem = ET.XML('<!DOCTYPE html PUBLIC'
...   ' "-//W3C//DTD XHTML 1.0 Transitional//EN"'
...   ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
...   '<html>text</html>')

Definition at line 1180 of file test_xml_etree.py.

01180 
01181 def doctype_public():
01182     """
01183     Test PUBLIC doctype.
01184 
01185     >>> elem = ET.XML('<!DOCTYPE html PUBLIC'
01186     ...   ' "-//W3C//DTD XHTML 1.0 Transitional//EN"'
01187     ...   ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
01188     ...   '<html>text</html>')
01189 
01190     """

Definition at line 904 of file test_xml_etree.py.

00904 
00905 def encoding():
00906     r"""
00907     Test encoding issues.
00908 
00909     >>> elem = ET.Element("tag")
00910     >>> elem.text = "abc"
00911     >>> serialize(elem)
00912     '<tag>abc</tag>'
00913     >>> serialize(elem, encoding="utf-8")
00914     b'<tag>abc</tag>'
00915     >>> serialize(elem, encoding="us-ascii")
00916     b'<tag>abc</tag>'
00917     >>> serialize(elem, encoding="iso-8859-1")
00918     b"<?xml version='1.0' encoding='iso-8859-1'?>\n<tag>abc</tag>"
00919 
00920     >>> elem.text = "<&\"\'>"
00921     >>> serialize(elem)
00922     '<tag>&lt;&amp;"\'&gt;</tag>'
00923     >>> serialize(elem, encoding="utf-8")
00924     b'<tag>&lt;&amp;"\'&gt;</tag>'
00925     >>> serialize(elem, encoding="us-ascii") # cdata characters
00926     b'<tag>&lt;&amp;"\'&gt;</tag>'
00927     >>> serialize(elem, encoding="iso-8859-1")
00928     b'<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>\n<tag>&lt;&amp;"\'&gt;</tag>'
00929 
00930     >>> elem.attrib["key"] = "<&\"\'>"
00931     >>> elem.text = None
00932     >>> serialize(elem)
00933     '<tag key="&lt;&amp;&quot;\'&gt;" />'
00934     >>> serialize(elem, encoding="utf-8")
00935     b'<tag key="&lt;&amp;&quot;\'&gt;" />'
00936     >>> serialize(elem, encoding="us-ascii")
00937     b'<tag key="&lt;&amp;&quot;\'&gt;" />'
00938     >>> serialize(elem, encoding="iso-8859-1")
00939     b'<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>\n<tag key="&lt;&amp;&quot;\'&gt;" />'
00940 
00941     >>> elem.text = '\xe5\xf6\xf6<>'
00942     >>> elem.attrib.clear()
00943     >>> serialize(elem)
00944     '<tag>\xe5\xf6\xf6&lt;&gt;</tag>'
00945     >>> serialize(elem, encoding="utf-8")
00946     b'<tag>\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;</tag>'
00947     >>> serialize(elem, encoding="us-ascii")
00948     b'<tag>&#229;&#246;&#246;&lt;&gt;</tag>'
00949     >>> serialize(elem, encoding="iso-8859-1")
00950     b"<?xml version='1.0' encoding='iso-8859-1'?>\n<tag>\xe5\xf6\xf6&lt;&gt;</tag>"
00951 
00952     >>> elem.attrib["key"] = '\xe5\xf6\xf6<>'
00953     >>> elem.text = None
00954     >>> serialize(elem)
00955     '<tag key="\xe5\xf6\xf6&lt;&gt;" />'
00956     >>> serialize(elem, encoding="utf-8")
00957     b'<tag key="\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;" />'
00958     >>> serialize(elem, encoding="us-ascii")
00959     b'<tag key="&#229;&#246;&#246;&lt;&gt;" />'
00960     >>> serialize(elem, encoding="iso-8859-1")
00961     b'<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>\n<tag key="\xe5\xf6\xf6&lt;&gt;" />'
00962     """

Test entity handling.

1) good entities

>>> e = ET.XML("<document title='&#x8230;'>test</document>")
>>> serialize(e, encoding="us-ascii")
b'<document title="&#33328;">test</document>'
>>> serialize(e)
'<document title="\u8230">test</document>'

2) bad entities

>>> normalize_exception(ET.XML, "<document>&entity;</document>")
Traceback (most recent call last):
ParseError: undefined entity: line 1, column 10

>>> normalize_exception(ET.XML, ENTITY_XML)
Traceback (most recent call last):
ParseError: undefined entity &entity;: line 5, column 10

3) custom entity

>>> parser = ET.XMLParser()
>>> parser.entity["entity"] = "text"
>>> parser.feed(ENTITY_XML)
>>> root = parser.close()
>>> serialize(root)
'<document>text</document>'

Definition at line 1019 of file test_xml_etree.py.

01019 
01020 def entity():
01021     """
01022     Test entity handling.
01023 
01024     1) good entities
01025 
01026     >>> e = ET.XML("<document title='&#x8230;'>test</document>")
01027     >>> serialize(e, encoding="us-ascii")
01028     b'<document title="&#33328;">test</document>'
01029     >>> serialize(e)
01030     '<document title="\u8230">test</document>'
01031 
01032     2) bad entities
01033 
01034     >>> normalize_exception(ET.XML, "<document>&entity;</document>")
01035     Traceback (most recent call last):
01036     ParseError: undefined entity: line 1, column 10
01037 
01038     >>> normalize_exception(ET.XML, ENTITY_XML)
01039     Traceback (most recent call last):
01040     ParseError: undefined entity &entity;: line 5, column 10
01041 
01042     3) custom entity
01043 
01044     >>> parser = ET.XMLParser()
01045     >>> parser.entity["entity"] = "text"
01046     >>> parser.feed(ENTITY_XML)
01047     >>> root = parser.close()
01048     >>> serialize(root)
01049     '<document>text</document>'
01050     """

Here is the caller graph for this function:

Test error handling.

>>> issubclass(ET.ParseError, SyntaxError)
True
>>> error("foo").position
(1, 0)
>>> error("<tag>&foo;</tag>").position
(1, 5)
>>> error("foobar<").position
(1, 6)

Definition at line 1051 of file test_xml_etree.py.

01051 
01052 def error(xml):
01053     """
01054 
01055     Test error handling.
01056 
01057     >>> issubclass(ET.ParseError, SyntaxError)
01058     True
01059     >>> error("foo").position
01060     (1, 0)
01061     >>> error("<tag>&foo;</tag>").position
01062     (1, 5)
01063     >>> error("foobar<").position
01064     (1, 6)
01065 
01066     """
01067     try:
01068         ET.XML(xml)
01069     except ET.ParseError:
01070         return sys.exc_info()[1]

>>> import io

>>> stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8"))
>>> tree = ET.ElementTree(file=stringfile)
>>> tree.find("tag").tag
'tag'
>>> tree.find("section/tag").tag
'tag'

>>> tree = ET.ElementTree(file=SIMPLE_XMLFILE)
>>> tree.find("element").tag
'element'
>>> tree.find("element/../empty-element").tag
'empty-element'

Definition at line 431 of file test_xml_etree.py.

00431 
00432 def file_init():
00433     """
00434     >>> import io
00435 
00436     >>> stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8"))
00437     >>> tree = ET.ElementTree(file=stringfile)
00438     >>> tree.find("tag").tag
00439     'tag'
00440     >>> tree.find("section/tag").tag
00441     'tag'
00442 
00443     >>> tree = ET.ElementTree(file=SIMPLE_XMLFILE)
00444     >>> tree.find("element").tag
00445     'element'
00446     >>> tree.find("element/../empty-element").tag
00447     'empty-element'
00448     """

Test find methods (including xpath syntax).

>>> elem = ET.XML(SAMPLE_XML)
>>> elem.find("tag").tag
'tag'
>>> ET.ElementTree(elem).find("tag").tag
'tag'
>>> elem.find("section/tag").tag
'tag'
>>> elem.find("./tag").tag
'tag'
>>> ET.ElementTree(elem).find("./tag").tag
'tag'
>>> ET.ElementTree(elem).find("/tag").tag
'tag'
>>> elem[2] = ET.XML(SAMPLE_SECTION)
>>> elem.find("section/nexttag").tag
'nexttag'
>>> ET.ElementTree(elem).find("section/tag").tag
'tag'
>>> ET.ElementTree(elem).find("tog")
>>> ET.ElementTree(elem).find("tog/foo")
>>> elem.findtext("tag")
'text'
>>> elem.findtext("section/nexttag")
''
>>> elem.findtext("section/nexttag", "default")
''
>>> elem.findtext("tog")
>>> elem.findtext("tog", "default")
'default'
>>> ET.ElementTree(elem).findtext("tag")
'text'
>>> ET.ElementTree(elem).findtext("tog/foo")
>>> ET.ElementTree(elem).findtext("tog/foo", "default")
'default'
>>> ET.ElementTree(elem).findtext("./tag")
'text'
>>> ET.ElementTree(elem).findtext("/tag")
'text'
>>> elem.findtext("section/tag")
'subtext'
>>> ET.ElementTree(elem).findtext("section/tag")
'subtext'
>>> summarize_list(elem.findall("."))
['body']
>>> summarize_list(elem.findall("tag"))
['tag', 'tag']
>>> summarize_list(elem.findall("tog"))
[]
>>> summarize_list(elem.findall("tog/foo"))
[]
>>> summarize_list(elem.findall("*"))
['tag', 'tag', 'section']
>>> summarize_list(elem.findall(".//tag"))
['tag', 'tag', 'tag', 'tag']
>>> summarize_list(elem.findall("section/tag"))
['tag']
>>> summarize_list(elem.findall("section//tag"))
['tag', 'tag']
>>> summarize_list(elem.findall("section/*"))
['tag', 'nexttag', 'nextsection']
>>> summarize_list(elem.findall("section//*"))
['tag', 'nexttag', 'nextsection', 'tag']
>>> summarize_list(elem.findall("section/.//*"))
['tag', 'nexttag', 'nextsection', 'tag']
>>> summarize_list(elem.findall("*/*"))
['tag', 'nexttag', 'nextsection']
>>> summarize_list(elem.findall("*//*"))
['tag', 'nexttag', 'nextsection', 'tag']
>>> summarize_list(elem.findall("*/tag"))
['tag']
>>> summarize_list(elem.findall("*/./tag"))
['tag']
>>> summarize_list(elem.findall("./tag"))
['tag', 'tag']
>>> summarize_list(elem.findall(".//tag"))
['tag', 'tag', 'tag', 'tag']
>>> summarize_list(elem.findall("././tag"))
['tag', 'tag']
>>> summarize_list(elem.findall(".//tag[@class]"))
['tag', 'tag', 'tag']
>>> summarize_list(elem.findall(".//tag[@class='a']"))
['tag']
>>> summarize_list(elem.findall(".//tag[@class='b']"))
['tag', 'tag']
>>> summarize_list(elem.findall(".//tag[@id]"))
['tag']
>>> summarize_list(elem.findall(".//section[tag]"))
['section']
>>> summarize_list(elem.findall(".//section[element]"))
[]
>>> summarize_list(elem.findall("../tag"))
[]
>>> summarize_list(elem.findall("section/../tag"))
['tag', 'tag']
>>> summarize_list(ET.ElementTree(elem).findall("./tag"))
['tag', 'tag']

Following example is invalid in 1.2.
A leading '*' is assumed in 1.3.

>>> elem.findall("section//") == elem.findall("section//*")
True

ET's Path module handles this case incorrectly; this gives
a warning in 1.3, and the behaviour will be modified in 1.4.

>>> summarize_list(ET.ElementTree(elem).findall("/tag"))
['tag', 'tag']

>>> elem = ET.XML(SAMPLE_XML_NS)
>>> summarize_list(elem.findall("tag"))
[]
>>> summarize_list(elem.findall("{http://effbot.org/ns}tag"))
['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']
>>> summarize_list(elem.findall(".//{http://effbot.org/ns}tag"))
['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']

Definition at line 309 of file test_xml_etree.py.

00309 
00310 def find():
00311     """
00312     Test find methods (including xpath syntax).
00313 
00314     >>> elem = ET.XML(SAMPLE_XML)
00315     >>> elem.find("tag").tag
00316     'tag'
00317     >>> ET.ElementTree(elem).find("tag").tag
00318     'tag'
00319     >>> elem.find("section/tag").tag
00320     'tag'
00321     >>> elem.find("./tag").tag
00322     'tag'
00323     >>> ET.ElementTree(elem).find("./tag").tag
00324     'tag'
00325     >>> ET.ElementTree(elem).find("/tag").tag
00326     'tag'
00327     >>> elem[2] = ET.XML(SAMPLE_SECTION)
00328     >>> elem.find("section/nexttag").tag
00329     'nexttag'
00330     >>> ET.ElementTree(elem).find("section/tag").tag
00331     'tag'
00332     >>> ET.ElementTree(elem).find("tog")
00333     >>> ET.ElementTree(elem).find("tog/foo")
00334     >>> elem.findtext("tag")
00335     'text'
00336     >>> elem.findtext("section/nexttag")
00337     ''
00338     >>> elem.findtext("section/nexttag", "default")
00339     ''
00340     >>> elem.findtext("tog")
00341     >>> elem.findtext("tog", "default")
00342     'default'
00343     >>> ET.ElementTree(elem).findtext("tag")
00344     'text'
00345     >>> ET.ElementTree(elem).findtext("tog/foo")
00346     >>> ET.ElementTree(elem).findtext("tog/foo", "default")
00347     'default'
00348     >>> ET.ElementTree(elem).findtext("./tag")
00349     'text'
00350     >>> ET.ElementTree(elem).findtext("/tag")
00351     'text'
00352     >>> elem.findtext("section/tag")
00353     'subtext'
00354     >>> ET.ElementTree(elem).findtext("section/tag")
00355     'subtext'
00356     >>> summarize_list(elem.findall("."))
00357     ['body']
00358     >>> summarize_list(elem.findall("tag"))
00359     ['tag', 'tag']
00360     >>> summarize_list(elem.findall("tog"))
00361     []
00362     >>> summarize_list(elem.findall("tog/foo"))
00363     []
00364     >>> summarize_list(elem.findall("*"))
00365     ['tag', 'tag', 'section']
00366     >>> summarize_list(elem.findall(".//tag"))
00367     ['tag', 'tag', 'tag', 'tag']
00368     >>> summarize_list(elem.findall("section/tag"))
00369     ['tag']
00370     >>> summarize_list(elem.findall("section//tag"))
00371     ['tag', 'tag']
00372     >>> summarize_list(elem.findall("section/*"))
00373     ['tag', 'nexttag', 'nextsection']
00374     >>> summarize_list(elem.findall("section//*"))
00375     ['tag', 'nexttag', 'nextsection', 'tag']
00376     >>> summarize_list(elem.findall("section/.//*"))
00377     ['tag', 'nexttag', 'nextsection', 'tag']
00378     >>> summarize_list(elem.findall("*/*"))
00379     ['tag', 'nexttag', 'nextsection']
00380     >>> summarize_list(elem.findall("*//*"))
00381     ['tag', 'nexttag', 'nextsection', 'tag']
00382     >>> summarize_list(elem.findall("*/tag"))
00383     ['tag']
00384     >>> summarize_list(elem.findall("*/./tag"))
00385     ['tag']
00386     >>> summarize_list(elem.findall("./tag"))
00387     ['tag', 'tag']
00388     >>> summarize_list(elem.findall(".//tag"))
00389     ['tag', 'tag', 'tag', 'tag']
00390     >>> summarize_list(elem.findall("././tag"))
00391     ['tag', 'tag']
00392     >>> summarize_list(elem.findall(".//tag[@class]"))
00393     ['tag', 'tag', 'tag']
00394     >>> summarize_list(elem.findall(".//tag[@class='a']"))
00395     ['tag']
00396     >>> summarize_list(elem.findall(".//tag[@class='b']"))
00397     ['tag', 'tag']
00398     >>> summarize_list(elem.findall(".//tag[@id]"))
00399     ['tag']
00400     >>> summarize_list(elem.findall(".//section[tag]"))
00401     ['section']
00402     >>> summarize_list(elem.findall(".//section[element]"))
00403     []
00404     >>> summarize_list(elem.findall("../tag"))
00405     []
00406     >>> summarize_list(elem.findall("section/../tag"))
00407     ['tag', 'tag']
00408     >>> summarize_list(ET.ElementTree(elem).findall("./tag"))
00409     ['tag', 'tag']
00410 
00411     Following example is invalid in 1.2.
00412     A leading '*' is assumed in 1.3.
00413 
00414     >>> elem.findall("section//") == elem.findall("section//*")
00415     True
00416 
00417     ET's Path module handles this case incorrectly; this gives
00418     a warning in 1.3, and the behaviour will be modified in 1.4.
00419 
00420     >>> summarize_list(ET.ElementTree(elem).findall("/tag"))
00421     ['tag', 'tag']
00422 
00423     >>> elem = ET.XML(SAMPLE_XML_NS)
00424     >>> summarize_list(elem.findall("tag"))
00425     []
00426     >>> summarize_list(elem.findall("{http://effbot.org/ns}tag"))
00427     ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']
00428     >>> summarize_list(elem.findall(".//{http://effbot.org/ns}tag"))
00429     ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']
00430     """

Test Element.getchildren()

>>> with open(SIMPLE_XMLFILE, "rb") as f:
...     tree = ET.parse(f)
>>> for elem in tree.getroot().iter():
...     summarize_list(elem.getchildren())
['element', 'element', 'empty-element']
[]
[]
[]
>>> for elem in tree.getiterator():
...     summarize_list(elem.getchildren())
['element', 'element', 'empty-element']
[]
[]
[]

>>> elem = ET.XML(SAMPLE_XML)
>>> len(elem.getchildren())
3
>>> len(elem[2].getchildren())
1
>>> elem[:] == elem.getchildren()
True
>>> child1 = elem[0]
>>> child2 = elem[2]
>>> del elem[1:2]
>>> len(elem.getchildren())
2
>>> child1 == elem[0]
True
>>> child2 == elem[1]
True
>>> elem[0:2] = [child2, child1]
>>> child2 == elem[0]
True
>>> child1 == elem[1]
True
>>> child1 == elem[0]
False
>>> elem.clear()
>>> elem.getchildren()
[]

Definition at line 836 of file test_xml_etree.py.

00836 
00837 def getchildren():
00838     """
00839     Test Element.getchildren()
00840 
00841     >>> with open(SIMPLE_XMLFILE, "rb") as f:
00842     ...     tree = ET.parse(f)
00843     >>> for elem in tree.getroot().iter():
00844     ...     summarize_list(elem.getchildren())
00845     ['element', 'element', 'empty-element']
00846     []
00847     []
00848     []
00849     >>> for elem in tree.getiterator():
00850     ...     summarize_list(elem.getchildren())
00851     ['element', 'element', 'empty-element']
00852     []
00853     []
00854     []
00855 
00856     >>> elem = ET.XML(SAMPLE_XML)
00857     >>> len(elem.getchildren())
00858     3
00859     >>> len(elem[2].getchildren())
00860     1
00861     >>> elem[:] == elem.getchildren()
00862     True
00863     >>> child1 = elem[0]
00864     >>> child2 = elem[2]
00865     >>> del elem[1:2]
00866     >>> len(elem.getchildren())
00867     2
00868     >>> child1 == elem[0]
00869     True
00870     >>> child2 == elem[1]
00871     True
00872     >>> elem[0:2] = [child2, child1]
00873     >>> child2 == elem[0]
00874     True
00875     >>> child1 == elem[1]
00876     True
00877     >>> child1 == elem[0]
00878     False
00879     >>> elem.clear()
00880     >>> elem.getchildren()
00881     []
00882     """

Test element tree interface.

>>> element = ET.Element("tag")
>>> check_element(element)
>>> tree = ET.ElementTree(element)
>>> check_element(tree.getroot())

>>> element = ET.Element("t\\xe4g", key="value")
>>> tree = ET.ElementTree(element)
>>> repr(element)   # doctest: +ELLIPSIS
"<Element 't\\xe4g' at 0x...>"
>>> element = ET.Element("tag", key="value")

Make sure all standard element methods exist.

>>> check_method(element.append)
>>> check_method(element.extend)
>>> check_method(element.insert)
>>> check_method(element.remove)
>>> check_method(element.getchildren)
>>> check_method(element.find)
>>> check_method(element.iterfind)
>>> check_method(element.findall)
>>> check_method(element.findtext)
>>> check_method(element.clear)
>>> check_method(element.get)
>>> check_method(element.set)
>>> check_method(element.keys)
>>> check_method(element.items)
>>> check_method(element.iter)
>>> check_method(element.itertext)
>>> check_method(element.getiterator)

These methods return an iterable. See bug 6472.

>>> check_method(element.iter("tag").__next__)
>>> check_method(element.iterfind("tag").__next__)
>>> check_method(element.iterfind("*").__next__)
>>> check_method(tree.iter("tag").__next__)
>>> check_method(tree.iterfind("tag").__next__)
>>> check_method(tree.iterfind("*").__next__)

These aliases are provided:

>>> assert ET.XML == ET.fromstring
>>> assert ET.PI == ET.ProcessingInstruction
>>> assert ET.XMLParser == ET.XMLTreeBuilder

Definition at line 154 of file test_xml_etree.py.

00154 
00155 def interface():
00156     """
00157     Test element tree interface.
00158 
00159     >>> element = ET.Element("tag")
00160     >>> check_element(element)
00161     >>> tree = ET.ElementTree(element)
00162     >>> check_element(tree.getroot())
00163 
00164     >>> element = ET.Element("t\\xe4g", key="value")
00165     >>> tree = ET.ElementTree(element)
00166     >>> repr(element)   # doctest: +ELLIPSIS
00167     "<Element 't\\xe4g' at 0x...>"
00168     >>> element = ET.Element("tag", key="value")
00169 
00170     Make sure all standard element methods exist.
00171 
00172     >>> check_method(element.append)
00173     >>> check_method(element.extend)
00174     >>> check_method(element.insert)
00175     >>> check_method(element.remove)
00176     >>> check_method(element.getchildren)
00177     >>> check_method(element.find)
00178     >>> check_method(element.iterfind)
00179     >>> check_method(element.findall)
00180     >>> check_method(element.findtext)
00181     >>> check_method(element.clear)
00182     >>> check_method(element.get)
00183     >>> check_method(element.set)
00184     >>> check_method(element.keys)
00185     >>> check_method(element.items)
00186     >>> check_method(element.iter)
00187     >>> check_method(element.itertext)
00188     >>> check_method(element.getiterator)
00189 
00190     These methods return an iterable. See bug 6472.
00191 
00192     >>> check_method(element.iter("tag").__next__)
00193     >>> check_method(element.iterfind("tag").__next__)
00194     >>> check_method(element.iterfind("*").__next__)
00195     >>> check_method(tree.iter("tag").__next__)
00196     >>> check_method(tree.iterfind("tag").__next__)
00197     >>> check_method(tree.iterfind("*").__next__)
00198 
00199     These aliases are provided:
00200 
00201     >>> assert ET.XML == ET.fromstring
00202     >>> assert ET.PI == ET.ProcessingInstruction
00203     >>> assert ET.XMLParser == ET.XMLTreeBuilder
00204     """

Test iterators.

>>> e = ET.XML("<html><body>this is a <i>paragraph</i>.</body>..</html>")
>>> summarize_list(e.iter())
['html', 'body', 'i']
>>> summarize_list(e.find("body").iter())
['body', 'i']
>>> summarize(next(e.iter()))
'html'
>>> "".join(e.itertext())
'this is a paragraph...'
>>> "".join(e.find("body").itertext())
'this is a paragraph.'
>>> next(e.itertext())
'this is a '

Method iterparse should return an iterator. See bug 6472.

>>> sourcefile = serialize(e, to_string=False)
>>> next(ET.iterparse(sourcefile))  # doctest: +ELLIPSIS
('end', <Element 'i' at 0x...>)

>>> tree = ET.ElementTree(None)
>>> tree.iter()
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'iter'

Definition at line 981 of file test_xml_etree.py.

00981 
00982 def iterators():
00983     """
00984     Test iterators.
00985 
00986     >>> e = ET.XML("<html><body>this is a <i>paragraph</i>.</body>..</html>")
00987     >>> summarize_list(e.iter())
00988     ['html', 'body', 'i']
00989     >>> summarize_list(e.find("body").iter())
00990     ['body', 'i']
00991     >>> summarize(next(e.iter()))
00992     'html'
00993     >>> "".join(e.itertext())
00994     'this is a paragraph...'
00995     >>> "".join(e.find("body").itertext())
00996     'this is a paragraph.'
00997     >>> next(e.itertext())
00998     'this is a '
00999 
01000     Method iterparse should return an iterator. See bug 6472.
01001 
01002     >>> sourcefile = serialize(e, to_string=False)
01003     >>> next(ET.iterparse(sourcefile))  # doctest: +ELLIPSIS
01004     ('end', <Element 'i' at 0x...>)
01005 
01006     >>> tree = ET.ElementTree(None)
01007     >>> tree.iter()
01008     Traceback (most recent call last):
01009     AttributeError: 'NoneType' object has no attribute 'iter'
01010     """

Test iterparse interface.

>>> iterparse = ET.iterparse

>>> context = iterparse(SIMPLE_XMLFILE)
>>> action, elem = next(context)
>>> print(action, elem.tag)
end element
>>> for action, elem in context:
...   print(action, elem.tag)
end element
end empty-element
end root
>>> context.root.tag
'root'

>>> context = iterparse(SIMPLE_NS_XMLFILE)
>>> for action, elem in context:
...   print(action, elem.tag)
end {namespace}element
end {namespace}element
end {namespace}empty-element
end {namespace}root

>>> events = ()
>>> context = iterparse(SIMPLE_XMLFILE, events)
>>> for action, elem in context:
...   print(action, elem.tag)

>>> events = ()
>>> context = iterparse(SIMPLE_XMLFILE, events=events)
>>> for action, elem in context:
...   print(action, elem.tag)

>>> events = ("start", "end")
>>> context = iterparse(SIMPLE_XMLFILE, events)
>>> for action, elem in context:
...   print(action, elem.tag)
start root
start element
end element
start element
end element
start empty-element
end empty-element
end root

>>> events = ("start", "end", "start-ns", "end-ns")
>>> context = iterparse(SIMPLE_NS_XMLFILE, events)
>>> for action, elem in context:
...   if action in ("start", "end"):
...     print(action, elem.tag)
...   else:
...     print(action, elem)
start-ns ('', 'namespace')
start {namespace}root
start {namespace}element
end {namespace}element
start {namespace}element
end {namespace}element
start {namespace}empty-element
end {namespace}empty-element
end {namespace}root
end-ns None

>>> events = ("start", "end", "bogus")
>>> with open(SIMPLE_XMLFILE, "rb") as f:
...     iterparse(f, events)
Traceback (most recent call last):
ValueError: unknown event 'bogus'

>>> import io

>>> source = io.BytesIO(
...     b"<?xml version='1.0' encoding='iso-8859-1'?>\\n"
...     b"<body xmlns='http://&#233;ffbot.org/ns'\\n"
...     b"      xmlns:cl\\xe9='http://effbot.org/ns'>text</body>\\n")
>>> events = ("start-ns",)
>>> context = iterparse(source, events)
>>> for action, elem in context:
...     print(action, elem)
start-ns ('', 'http://\\xe9ffbot.org/ns')
start-ns ('cl\\xe9', 'http://effbot.org/ns')

>>> source = io.StringIO("<document />junk")
>>> try:
...   for action, elem in iterparse(source):
...     print(action, elem.tag)
... except ET.ParseError as v:
...   print(v)
junk after document element: line 1, column 12

Definition at line 665 of file test_xml_etree.py.

00665 
00666 def iterparse():
00667     """
00668     Test iterparse interface.
00669 
00670     >>> iterparse = ET.iterparse
00671 
00672     >>> context = iterparse(SIMPLE_XMLFILE)
00673     >>> action, elem = next(context)
00674     >>> print(action, elem.tag)
00675     end element
00676     >>> for action, elem in context:
00677     ...   print(action, elem.tag)
00678     end element
00679     end empty-element
00680     end root
00681     >>> context.root.tag
00682     'root'
00683 
00684     >>> context = iterparse(SIMPLE_NS_XMLFILE)
00685     >>> for action, elem in context:
00686     ...   print(action, elem.tag)
00687     end {namespace}element
00688     end {namespace}element
00689     end {namespace}empty-element
00690     end {namespace}root
00691 
00692     >>> events = ()
00693     >>> context = iterparse(SIMPLE_XMLFILE, events)
00694     >>> for action, elem in context:
00695     ...   print(action, elem.tag)
00696 
00697     >>> events = ()
00698     >>> context = iterparse(SIMPLE_XMLFILE, events=events)
00699     >>> for action, elem in context:
00700     ...   print(action, elem.tag)
00701 
00702     >>> events = ("start", "end")
00703     >>> context = iterparse(SIMPLE_XMLFILE, events)
00704     >>> for action, elem in context:
00705     ...   print(action, elem.tag)
00706     start root
00707     start element
00708     end element
00709     start element
00710     end element
00711     start empty-element
00712     end empty-element
00713     end root
00714 
00715     >>> events = ("start", "end", "start-ns", "end-ns")
00716     >>> context = iterparse(SIMPLE_NS_XMLFILE, events)
00717     >>> for action, elem in context:
00718     ...   if action in ("start", "end"):
00719     ...     print(action, elem.tag)
00720     ...   else:
00721     ...     print(action, elem)
00722     start-ns ('', 'namespace')
00723     start {namespace}root
00724     start {namespace}element
00725     end {namespace}element
00726     start {namespace}element
00727     end {namespace}element
00728     start {namespace}empty-element
00729     end {namespace}empty-element
00730     end {namespace}root
00731     end-ns None
00732 
00733     >>> events = ("start", "end", "bogus")
00734     >>> with open(SIMPLE_XMLFILE, "rb") as f:
00735     ...     iterparse(f, events)
00736     Traceback (most recent call last):
00737     ValueError: unknown event 'bogus'
00738 
00739     >>> import io
00740 
00741     >>> source = io.BytesIO(
00742     ...     b"<?xml version='1.0' encoding='iso-8859-1'?>\\n"
00743     ...     b"<body xmlns='http://&#233;ffbot.org/ns'\\n"
00744     ...     b"      xmlns:cl\\xe9='http://effbot.org/ns'>text</body>\\n")
00745     >>> events = ("start-ns",)
00746     >>> context = iterparse(source, events)
00747     >>> for action, elem in context:
00748     ...     print(action, elem)
00749     start-ns ('', 'http://\\xe9ffbot.org/ns')
00750     start-ns ('cl\\xe9', 'http://effbot.org/ns')
00751 
00752     >>> source = io.StringIO("<document />junk")
00753     >>> try:
00754     ...   for action, elem in iterparse(source):
00755     ...     print(action, elem.tag)
00756     ... except ET.ParseError as v:
00757     ...   print(v)
00758     junk after document element: line 1, column 12
00759     """

Test makeelement handling.

>>> elem = ET.Element("tag")
>>> attrib = {"key": "value"}
>>> subelem = elem.makeelement("subtag", attrib)
>>> if subelem.attrib is attrib:
...     print("attrib aliasing")
>>> elem.append(subelem)
>>> serialize(elem)
'<tag><subtag key="value" /></tag>'

>>> elem.clear()
>>> serialize(elem)
'<tag />'
>>> elem.append(subelem)
>>> serialize(elem)
'<tag><subtag key="value" /></tag>'
>>> elem.extend([subelem, subelem])
>>> serialize(elem)
'<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>'
>>> elem[:] = [subelem]
>>> serialize(elem)
'<tag><subtag key="value" /></tag>'
>>> elem[:] = tuple([subelem])
>>> serialize(elem)
'<tag><subtag key="value" /></tag>'

Definition at line 553 of file test_xml_etree.py.

00553 
00554 def makeelement():
00555     """
00556     Test makeelement handling.
00557 
00558     >>> elem = ET.Element("tag")
00559     >>> attrib = {"key": "value"}
00560     >>> subelem = elem.makeelement("subtag", attrib)
00561     >>> if subelem.attrib is attrib:
00562     ...     print("attrib aliasing")
00563     >>> elem.append(subelem)
00564     >>> serialize(elem)
00565     '<tag><subtag key="value" /></tag>'
00566 
00567     >>> elem.clear()
00568     >>> serialize(elem)
00569     '<tag />'
00570     >>> elem.append(subelem)
00571     >>> serialize(elem)
00572     '<tag><subtag key="value" /></tag>'
00573     >>> elem.extend([subelem, subelem])
00574     >>> serialize(elem)
00575     '<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>'
00576     >>> elem[:] = [subelem]
00577     >>> serialize(elem)
00578     '<tag><subtag key="value" /></tag>'
00579     >>> elem[:] = tuple([subelem])
00580     >>> serialize(elem)
00581     '<tag><subtag key="value" /></tag>'
00582 
00583     """

Definition at line 963 of file test_xml_etree.py.

00963 
00964 def methods():
00965     r"""
00966     Test serialization methods.
00967 
00968     >>> e = ET.XML("<html><link/><script>1 &lt; 2</script></html>")
00969     >>> e.tail = "\n"
00970     >>> serialize(e)
00971     '<html><link /><script>1 &lt; 2</script></html>\n'
00972     >>> serialize(e, method=None)
00973     '<html><link /><script>1 &lt; 2</script></html>\n'
00974     >>> serialize(e, method="xml")
00975     '<html><link /><script>1 &lt; 2</script></html>\n'
00976     >>> serialize(e, method="html")
00977     '<html><link><script>1 < 2</script></html>\n'
00978     >>> serialize(e, method="text")
00979     '1 < 2\n'
00980     """

Here is the caller graph for this function:

Test namespace issues.

1) xml namespace

>>> elem = ET.XML("<tag xml:lang='en' />")
>>> serialize(elem) # 1.1
'<tag xml:lang="en" />'

2) other "well-known" namespaces

>>> elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />")
>>> serialize(elem) # 2.1
'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />'

>>> elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />")
>>> serialize(elem) # 2.2
'<html:html xmlns:html="http://www.w3.org/1999/xhtml" />'

>>> elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />")
>>> serialize(elem) # 2.3
'<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />'

3) unknown namespaces
>>> elem = ET.XML(SAMPLE_XML_NS)
>>> print(serialize(elem))
<ns0:body xmlns:ns0="http://effbot.org/ns">
  <ns0:tag>text</ns0:tag>
  <ns0:tag />
  <ns0:section>
    <ns0:tag>subtext</ns0:tag>
  </ns0:section>
</ns0:body>

Definition at line 1071 of file test_xml_etree.py.

01071 
01072 def namespace():
01073     """
01074     Test namespace issues.
01075 
01076     1) xml namespace
01077 
01078     >>> elem = ET.XML("<tag xml:lang='en' />")
01079     >>> serialize(elem) # 1.1
01080     '<tag xml:lang="en" />'
01081 
01082     2) other "well-known" namespaces
01083 
01084     >>> elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />")
01085     >>> serialize(elem) # 2.1
01086     '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />'
01087 
01088     >>> elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />")
01089     >>> serialize(elem) # 2.2
01090     '<html:html xmlns:html="http://www.w3.org/1999/xhtml" />'
01091 
01092     >>> elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />")
01093     >>> serialize(elem) # 2.3
01094     '<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />'
01095 
01096     3) unknown namespaces
01097     >>> elem = ET.XML(SAMPLE_XML_NS)
01098     >>> print(serialize(elem))
01099     <ns0:body xmlns:ns0="http://effbot.org/ns">
01100       <ns0:tag>text</ns0:tag>
01101       <ns0:tag />
01102       <ns0:section>
01103         <ns0:tag>subtext</ns0:tag>
01104       </ns0:section>
01105     </ns0:body>
01106     """

Definition at line 96 of file test_xml_etree.py.

00096 
00097 def normalize_crlf(tree):
00098     for elem in tree.iter():
00099         if elem.text:
00100             elem.text = elem.text.replace("\r\n", "\n")
00101         if elem.tail:
00102             elem.tail = elem.tail.replace("\r\n", "\n")

def test.test_xml_etree.normalize_exception (   func,
  args,
  kwargs 
)

Definition at line 103 of file test_xml_etree.py.

00103 
00104 def normalize_exception(func, *args, **kwargs):
00105     # Ignore the exception __module__
00106     try:
00107         func(*args, **kwargs)
00108     except Exception as err:
00109         print("Traceback (most recent call last):")
00110         print("{}: {}".format(err.__class__.__name__, err))

Test parsing from file.

>>> tree = ET.parse(SIMPLE_XMLFILE)
>>> normalize_crlf(tree)
>>> tree.write(sys.stdout, encoding='unicode')
<root>
   <element key="value">text</element>
   <element>text</element>tail
   <empty-element />
</root>
>>> tree = ET.parse(SIMPLE_NS_XMLFILE)
>>> normalize_crlf(tree)
>>> tree.write(sys.stdout, encoding='unicode')
<ns0:root xmlns:ns0="namespace">
   <ns0:element key="value">text</ns0:element>
   <ns0:element>text</ns0:element>tail
   <ns0:empty-element />
</ns0:root>

>>> with open(SIMPLE_XMLFILE) as f:
...     data = f.read()

>>> parser = ET.XMLParser()
>>> parser.version  # doctest: +ELLIPSIS
'Expat ...'
>>> parser.feed(data)
>>> print(serialize(parser.close()))
<root>
   <element key="value">text</element>
   <element>text</element>tail
   <empty-element />
</root>

>>> parser = ET.XMLTreeBuilder() # 1.2 compatibility
>>> parser.feed(data)
>>> print(serialize(parser.close()))
<root>
   <element key="value">text</element>
   <element>text</element>tail
   <empty-element />
</root>

>>> target = ET.TreeBuilder()
>>> parser = ET.XMLParser(target=target)
>>> parser.feed(data)
>>> print(serialize(parser.close()))
<root>
   <element key="value">text</element>
   <element>text</element>tail
   <empty-element />
</root>

Definition at line 584 of file test_xml_etree.py.

00584 
00585 def parsefile():
00586     """
00587     Test parsing from file.
00588 
00589     >>> tree = ET.parse(SIMPLE_XMLFILE)
00590     >>> normalize_crlf(tree)
00591     >>> tree.write(sys.stdout, encoding='unicode')
00592     <root>
00593        <element key="value">text</element>
00594        <element>text</element>tail
00595        <empty-element />
00596     </root>
00597     >>> tree = ET.parse(SIMPLE_NS_XMLFILE)
00598     >>> normalize_crlf(tree)
00599     >>> tree.write(sys.stdout, encoding='unicode')
00600     <ns0:root xmlns:ns0="namespace">
00601        <ns0:element key="value">text</ns0:element>
00602        <ns0:element>text</ns0:element>tail
00603        <ns0:empty-element />
00604     </ns0:root>
00605 
00606     >>> with open(SIMPLE_XMLFILE) as f:
00607     ...     data = f.read()
00608 
00609     >>> parser = ET.XMLParser()
00610     >>> parser.version  # doctest: +ELLIPSIS
00611     'Expat ...'
00612     >>> parser.feed(data)
00613     >>> print(serialize(parser.close()))
00614     <root>
00615        <element key="value">text</element>
00616        <element>text</element>tail
00617        <empty-element />
00618     </root>
00619 
00620     >>> parser = ET.XMLTreeBuilder() # 1.2 compatibility
00621     >>> parser.feed(data)
00622     >>> print(serialize(parser.close()))
00623     <root>
00624        <element key="value">text</element>
00625        <element>text</element>tail
00626        <empty-element />
00627     </root>
00628 
00629     >>> target = ET.TreeBuilder()
00630     >>> parser = ET.XMLParser(target=target)
00631     >>> parser.feed(data)
00632     >>> print(serialize(parser.close()))
00633     <root>
00634        <element key="value">text</element>
00635        <element>text</element>tail
00636        <empty-element />
00637     </root>
00638     """

Here is the caller graph for this function:

>>> element = ET.XML("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
<html><body>text</body></html>
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
<html><body>text</body></html>
>>> sequence = ["<html><body>", "text</bo", "dy></html>"]
>>> element = ET.fromstringlist(sequence)
>>> ET.tostring(element)
b'<html><body>text</body></html>'
>>> b"".join(ET.tostringlist(element))
b'<html><body>text</body></html>'
>>> ET.tostring(element, "ascii")
b"<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
>>> len(ids)
0
>>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
>>> len(ids)
1
>>> ids["body"].tag
'body'

Definition at line 639 of file test_xml_etree.py.

00639 
00640 def parseliteral():
00641     """
00642     >>> element = ET.XML("<html><body>text</body></html>")
00643     >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
00644     <html><body>text</body></html>
00645     >>> element = ET.fromstring("<html><body>text</body></html>")
00646     >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
00647     <html><body>text</body></html>
00648     >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
00649     >>> element = ET.fromstringlist(sequence)
00650     >>> ET.tostring(element)
00651     b'<html><body>text</body></html>'
00652     >>> b"".join(ET.tostringlist(element))
00653     b'<html><body>text</body></html>'
00654     >>> ET.tostring(element, "ascii")
00655     b"<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
00656     >>> _, ids = ET.XMLID("<html><body>text</body></html>")
00657     >>> len(ids)
00658     0
00659     >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
00660     >>> len(ids)
00661     1
00662     >>> ids["body"].tag
00663     'body'
00664     """

Check that the path cache behaves sanely.

>>> elem = ET.XML(SAMPLE_XML)
>>> for i in range(10): ET.ElementTree(elem).find('./'+str(i))
>>> cache_len_10 = len(ET.ElementPath._cache)
>>> for i in range(10): ET.ElementTree(elem).find('./'+str(i))
>>> len(ET.ElementPath._cache) == cache_len_10
True
>>> for i in range(20): ET.ElementTree(elem).find('./'+str(i))
>>> len(ET.ElementPath._cache) > cache_len_10
True
>>> for i in range(600): ET.ElementTree(elem).find('./'+str(i))
>>> len(ET.ElementPath._cache) < 500
True

Definition at line 459 of file test_xml_etree.py.

00459 
00460 def path_cache():
00461     """
00462     Check that the path cache behaves sanely.
00463 
00464     >>> elem = ET.XML(SAMPLE_XML)
00465     >>> for i in range(10): ET.ElementTree(elem).find('./'+str(i))
00466     >>> cache_len_10 = len(ET.ElementPath._cache)
00467     >>> for i in range(10): ET.ElementTree(elem).find('./'+str(i))
00468     >>> len(ET.ElementPath._cache) == cache_len_10
00469     True
00470     >>> for i in range(20): ET.ElementTree(elem).find('./'+str(i))
00471     >>> len(ET.ElementPath._cache) > cache_len_10
00472     True
00473     >>> for i in range(600): ET.ElementTree(elem).find('./'+str(i))
00474     >>> len(ET.ElementPath._cache) < 500
00475     True
00476     """

Test ProcessingInstruction directly

>>> ET.tostring(ET.ProcessingInstruction('test', 'instruction'))
b'<?test instruction?>'
>>> ET.tostring(ET.PI('test', 'instruction'))
b'<?test instruction?>'

Issue #2746

>>> ET.tostring(ET.PI('test', '<testing&>'))
b'<?test <testing&>?>'
>>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"

Definition at line 1245 of file test_xml_etree.py.

01245 
01246 def processinginstruction():
01247     """
01248     Test ProcessingInstruction directly
01249 
01250     >>> ET.tostring(ET.ProcessingInstruction('test', 'instruction'))
01251     b'<?test instruction?>'
01252     >>> ET.tostring(ET.PI('test', 'instruction'))
01253     b'<?test instruction?>'
01254 
01255     Issue #2746
01256 
01257     >>> ET.tostring(ET.PI('test', '<testing&>'))
01258     b'<?test <testing&>?>'
01259     >>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
01260     b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"
01261     """
01262 
01263 #
01264 # xinclude tests (samples from appendix C of the xinclude specification)

Test QName handling.

1) decorated tags

>>> elem = ET.Element("{uri}tag")
>>> serialize(elem) # 1.1
'<ns0:tag xmlns:ns0="uri" />'
>>> elem = ET.Element(ET.QName("{uri}tag"))
>>> serialize(elem) # 1.2
'<ns0:tag xmlns:ns0="uri" />'
>>> elem = ET.Element(ET.QName("uri", "tag"))
>>> serialize(elem) # 1.3
'<ns0:tag xmlns:ns0="uri" />'
>>> elem = ET.Element(ET.QName("uri", "tag"))
>>> subelem = ET.SubElement(elem, ET.QName("uri", "tag1"))
>>> subelem = ET.SubElement(elem, ET.QName("uri", "tag2"))
>>> serialize(elem) # 1.4
'<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>'

2) decorated attributes

>>> elem.clear()
>>> elem.attrib["{uri}key"] = "value"
>>> serialize(elem) # 2.1
'<ns0:tag xmlns:ns0="uri" ns0:key="value" />'

>>> elem.clear()
>>> elem.attrib[ET.QName("{uri}key")] = "value"
>>> serialize(elem) # 2.2
'<ns0:tag xmlns:ns0="uri" ns0:key="value" />'

3) decorated values are not converted by default, but the
   QName wrapper can be used for values

>>> elem.clear()
>>> elem.attrib["{uri}key"] = "{uri}value"
>>> serialize(elem) # 3.1
'<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />'

>>> elem.clear()
>>> elem.attrib["{uri}key"] = ET.QName("{uri}value")
>>> serialize(elem) # 3.2
'<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />'

>>> elem.clear()
>>> subelem = ET.Element("tag")
>>> subelem.attrib["{uri1}key"] = ET.QName("{uri2}value")
>>> elem.append(subelem)
>>> elem.append(subelem)
>>> serialize(elem) # 3.3
'<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2"><tag ns1:key="ns2:value" /><tag ns1:key="ns2:value" /></ns0:tag>'

4) Direct QName tests

>>> str(ET.QName('ns', 'tag'))
'{ns}tag'
>>> str(ET.QName('{ns}tag'))
'{ns}tag'
>>> q1 = ET.QName('ns', 'tag')
>>> q2 = ET.QName('ns', 'tag')
>>> q1 == q2
True
>>> q2 = ET.QName('ns', 'other-tag')
>>> q1 == q2
False
>>> q1 == 'ns:tag'
False
>>> q1 == '{ns}tag'
True

Definition at line 1107 of file test_xml_etree.py.

01107 
01108 def qname():
01109     """
01110     Test QName handling.
01111 
01112     1) decorated tags
01113 
01114     >>> elem = ET.Element("{uri}tag")
01115     >>> serialize(elem) # 1.1
01116     '<ns0:tag xmlns:ns0="uri" />'
01117     >>> elem = ET.Element(ET.QName("{uri}tag"))
01118     >>> serialize(elem) # 1.2
01119     '<ns0:tag xmlns:ns0="uri" />'
01120     >>> elem = ET.Element(ET.QName("uri", "tag"))
01121     >>> serialize(elem) # 1.3
01122     '<ns0:tag xmlns:ns0="uri" />'
01123     >>> elem = ET.Element(ET.QName("uri", "tag"))
01124     >>> subelem = ET.SubElement(elem, ET.QName("uri", "tag1"))
01125     >>> subelem = ET.SubElement(elem, ET.QName("uri", "tag2"))
01126     >>> serialize(elem) # 1.4
01127     '<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>'
01128 
01129     2) decorated attributes
01130 
01131     >>> elem.clear()
01132     >>> elem.attrib["{uri}key"] = "value"
01133     >>> serialize(elem) # 2.1
01134     '<ns0:tag xmlns:ns0="uri" ns0:key="value" />'
01135 
01136     >>> elem.clear()
01137     >>> elem.attrib[ET.QName("{uri}key")] = "value"
01138     >>> serialize(elem) # 2.2
01139     '<ns0:tag xmlns:ns0="uri" ns0:key="value" />'
01140 
01141     3) decorated values are not converted by default, but the
01142        QName wrapper can be used for values
01143 
01144     >>> elem.clear()
01145     >>> elem.attrib["{uri}key"] = "{uri}value"
01146     >>> serialize(elem) # 3.1
01147     '<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />'
01148 
01149     >>> elem.clear()
01150     >>> elem.attrib["{uri}key"] = ET.QName("{uri}value")
01151     >>> serialize(elem) # 3.2
01152     '<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />'
01153 
01154     >>> elem.clear()
01155     >>> subelem = ET.Element("tag")
01156     >>> subelem.attrib["{uri1}key"] = ET.QName("{uri2}value")
01157     >>> elem.append(subelem)
01158     >>> elem.append(subelem)
01159     >>> serialize(elem) # 3.3
01160     '<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2"><tag ns1:key="ns2:value" /><tag ns1:key="ns2:value" /></ns0:tag>'
01161 
01162     4) Direct QName tests
01163 
01164     >>> str(ET.QName('ns', 'tag'))
01165     '{ns}tag'
01166     >>> str(ET.QName('{ns}tag'))
01167     '{ns}tag'
01168     >>> q1 = ET.QName('ns', 'tag')
01169     >>> q2 = ET.QName('ns', 'tag')
01170     >>> q1 == q2
01171     True
01172     >>> q2 = ET.QName('ns', 'other-tag')
01173     >>> q1 == q2
01174     False
01175     >>> q1 == 'ns:tag'
01176     False
01177     >>> q1 == '{ns}tag'
01178     True
01179     """

Import sanity.

>>> from xml.etree import ElementTree
>>> from xml.etree import ElementInclude
>>> from xml.etree import ElementPath

Definition at line 61 of file test_xml_etree.py.

00061 
00062 def sanity():
00063     """
00064     Import sanity.
00065 
00066     >>> from xml.etree import ElementTree
00067     >>> from xml.etree import ElementInclude
00068     >>> from xml.etree import ElementPath
00069     """

def test.test_xml_etree.serialize (   elem,
  to_string = True,
  encoding = 'unicode',
  options 
)

Definition at line 74 of file test_xml_etree.py.

00074 
00075 def serialize(elem, to_string=True, encoding='unicode', **options):
00076     import io
00077     if encoding != 'unicode':
00078         file = io.BytesIO()
00079     else:
00080         file = io.StringIO()
00081     tree = ET.ElementTree(elem)
00082     tree.write(file, encoding=encoding, **options)
00083     if to_string:
00084         return file.getvalue()
00085     else:
00086         file.seek(0)
00087         return file

Here is the caller graph for this function:

Test find methods using the elementpath fallback.

>>> from xml.etree import ElementTree

>>> CurrentElementPath = ElementTree.ElementPath
>>> ElementTree.ElementPath = ElementTree._SimpleElementPath()
>>> elem = ElementTree.XML(SAMPLE_XML)
>>> elem.find("tag").tag
'tag'
>>> ElementTree.ElementTree(elem).find("tag").tag
'tag'
>>> elem.findtext("tag")
'text'
>>> elem.findtext("tog")
>>> elem.findtext("tog", "default")
'default'
>>> ElementTree.ElementTree(elem).findtext("tag")
'text'
>>> summarize_list(elem.findall("tag"))
['tag', 'tag']
>>> summarize_list(elem.findall(".//tag"))
['tag', 'tag', 'tag']

Path syntax doesn't work in this case.

>>> elem.find("section/tag")
>>> elem.findtext("section/tag")
>>> summarize_list(elem.findall("section/tag"))
[]

>>> ElementTree.ElementPath = CurrentElementPath

Definition at line 274 of file test_xml_etree.py.

00274 
00275 def simplefind():
00276     """
00277     Test find methods using the elementpath fallback.
00278 
00279     >>> from xml.etree import ElementTree
00280 
00281     >>> CurrentElementPath = ElementTree.ElementPath
00282     >>> ElementTree.ElementPath = ElementTree._SimpleElementPath()
00283     >>> elem = ElementTree.XML(SAMPLE_XML)
00284     >>> elem.find("tag").tag
00285     'tag'
00286     >>> ElementTree.ElementTree(elem).find("tag").tag
00287     'tag'
00288     >>> elem.findtext("tag")
00289     'text'
00290     >>> elem.findtext("tog")
00291     >>> elem.findtext("tog", "default")
00292     'default'
00293     >>> ElementTree.ElementTree(elem).findtext("tag")
00294     'text'
00295     >>> summarize_list(elem.findall("tag"))
00296     ['tag', 'tag']
00297     >>> summarize_list(elem.findall(".//tag"))
00298     ['tag', 'tag', 'tag']
00299 
00300     Path syntax doesn't work in this case.
00301 
00302     >>> elem.find("section/tag")
00303     >>> elem.findtext("section/tag")
00304     >>> summarize_list(elem.findall("section/tag"))
00305     []
00306 
00307     >>> ElementTree.ElementPath = CurrentElementPath
00308     """

Basic method sanity checks.

>>> elem = ET.XML("<body><tag/></body>")
>>> serialize(elem)
'<body><tag /></body>'
>>> e = ET.Element("tag2")
>>> elem.append(e)
>>> serialize(elem)
'<body><tag /><tag2 /></body>'
>>> elem.remove(e)
>>> serialize(elem)
'<body><tag /></body>'
>>> elem.insert(0, e)
>>> serialize(elem)
'<body><tag2 /><tag /></body>'
>>> elem.remove(e)
>>> elem.extend([e])
>>> serialize(elem)
'<body><tag /><tag2 /></body>'
>>> elem.remove(e)

>>> element = ET.Element("tag", key="value")
>>> serialize(element) # 1
'<tag key="value" />'
>>> subelement = ET.Element("subtag")
>>> element.append(subelement)
>>> serialize(element) # 2
'<tag key="value"><subtag /></tag>'
>>> element.insert(0, subelement)
>>> serialize(element) # 3
'<tag key="value"><subtag /><subtag /></tag>'
>>> element.remove(subelement)
>>> serialize(element) # 4
'<tag key="value"><subtag /></tag>'
>>> element.remove(subelement)
>>> serialize(element) # 5
'<tag key="value" />'
>>> element.remove(subelement)
Traceback (most recent call last):
ValueError: list.remove(x): x not in list
>>> serialize(element) # 6
'<tag key="value" />'
>>> element[0:0] = [subelement, subelement, subelement]
>>> serialize(element[1])
'<subtag />'
>>> element[1:9] == [element[1], element[2]]
True
>>> element[:9:2] == [element[0], element[2]]
True
>>> del element[1:2]
>>> serialize(element)
'<tag key="value"><subtag /><subtag /></tag>'

Definition at line 205 of file test_xml_etree.py.

00205 
00206 def simpleops():
00207     """
00208     Basic method sanity checks.
00209 
00210     >>> elem = ET.XML("<body><tag/></body>")
00211     >>> serialize(elem)
00212     '<body><tag /></body>'
00213     >>> e = ET.Element("tag2")
00214     >>> elem.append(e)
00215     >>> serialize(elem)
00216     '<body><tag /><tag2 /></body>'
00217     >>> elem.remove(e)
00218     >>> serialize(elem)
00219     '<body><tag /></body>'
00220     >>> elem.insert(0, e)
00221     >>> serialize(elem)
00222     '<body><tag2 /><tag /></body>'
00223     >>> elem.remove(e)
00224     >>> elem.extend([e])
00225     >>> serialize(elem)
00226     '<body><tag /><tag2 /></body>'
00227     >>> elem.remove(e)
00228 
00229     >>> element = ET.Element("tag", key="value")
00230     >>> serialize(element) # 1
00231     '<tag key="value" />'
00232     >>> subelement = ET.Element("subtag")
00233     >>> element.append(subelement)
00234     >>> serialize(element) # 2
00235     '<tag key="value"><subtag /></tag>'
00236     >>> element.insert(0, subelement)
00237     >>> serialize(element) # 3
00238     '<tag key="value"><subtag /><subtag /></tag>'
00239     >>> element.remove(subelement)
00240     >>> serialize(element) # 4
00241     '<tag key="value"><subtag /></tag>'
00242     >>> element.remove(subelement)
00243     >>> serialize(element) # 5
00244     '<tag key="value" />'
00245     >>> element.remove(subelement)
00246     Traceback (most recent call last):
00247     ValueError: list.remove(x): x not in list
00248     >>> serialize(element) # 6
00249     '<tag key="value" />'
00250     >>> element[0:0] = [subelement, subelement, subelement]
00251     >>> serialize(element[1])
00252     '<subtag />'
00253     >>> element[1:9] == [element[1], element[2]]
00254     True
00255     >>> element[:9:2] == [element[0], element[2]]
00256     True
00257     >>> del element[1:2]
00258     >>> serialize(element)
00259     '<tag key="value"><subtag /><subtag /></tag>'
00260     """

Definition at line 88 of file test_xml_etree.py.

00088 
00089 def summarize(elem):
00090     if elem.tag == ET.Comment:
00091         return "<Comment>"
00092     return elem.tag

Here is the caller graph for this function:

Definition at line 93 of file test_xml_etree.py.

00093 
00094 def summarize_list(seq):
00095     return [summarize(elem) for elem in seq]

Here is the call graph for this function:

def test.test_xml_etree.test_main (   module_name = 'xml.etree.ElementTree')

Definition at line 1898 of file test_xml_etree.py.

01898 
01899 def test_main(module_name='xml.etree.ElementTree'):
01900     from test import test_xml_etree
01901 
01902     use_py_module = (module_name == 'xml.etree.ElementTree')
01903 
01904     # The same doctests are used for both the Python and the C implementations
01905     assert test_xml_etree.ET.__name__ == module_name
01906 
01907     # XXX the C module should give the same warnings as the Python module
01908     with CleanContext(quiet=not use_py_module):
01909         support.run_doctest(test_xml_etree, verbosity=True)
01910 
01911     # The module should not be changed by the tests
01912     assert test_xml_etree.ET.__name__ == module_name

>>> elem = ET.Element("tag")
>>> elem.text = "text"
>>> serialize(elem)
'<tag>text</tag>'
>>> ET.SubElement(elem, "subtag").text = "subtext"
>>> serialize(elem)
'<tag>text<subtag>subtext</subtag></tag>'

Test tag suppression
>>> elem.tag = None
>>> serialize(elem)
'text<subtag>subtext</subtag>'
>>> elem.insert(0, ET.Comment("comment"))
>>> serialize(elem)     # assumes 1.3
'text<!--comment--><subtag>subtext</subtag>'
>>> elem[0] = ET.PI("key", "value")
>>> serialize(elem)
'text<?key value?><subtag>subtext</subtag>'

Definition at line 760 of file test_xml_etree.py.

00760 
00761 def writefile():
00762     """
00763     >>> elem = ET.Element("tag")
00764     >>> elem.text = "text"
00765     >>> serialize(elem)
00766     '<tag>text</tag>'
00767     >>> ET.SubElement(elem, "subtag").text = "subtext"
00768     >>> serialize(elem)
00769     '<tag>text<subtag>subtext</subtag></tag>'
00770 
00771     Test tag suppression
00772     >>> elem.tag = None
00773     >>> serialize(elem)
00774     'text<subtag>subtext</subtag>'
00775     >>> elem.insert(0, ET.Comment("comment"))
00776     >>> serialize(elem)     # assumes 1.3
00777     'text<!--comment--><subtag>subtext</subtag>'
00778     >>> elem[0] = ET.PI("key", "value")
00779     >>> serialize(elem)
00780     'text<?key value?><subtag>subtext</subtag>'
00781     """

>>> elem = ET.XML("<html><body>text</body></html>")
>>> ET.tostring(elem)
b'<html><body>text</body></html>'
>>> elem = ET.fromstring("<html><body>text</body></html>")
>>> ET.tostring(elem)
b'<html><body>text</body></html>'

Definition at line 883 of file test_xml_etree.py.

00883 
00884 def writestring():
00885     """
00886     >>> elem = ET.XML("<html><body>text</body></html>")
00887     >>> ET.tostring(elem)
00888     b'<html><body>text</body></html>'
00889     >>> elem = ET.fromstring("<html><body>text</body></html>")
00890     >>> ET.tostring(elem)
00891     b'<html><body>text</body></html>'
00892     """

Definition at line 1348 of file test_xml_etree.py.

01348 
01349 def xinclude():
01350     r"""
01351     Basic inclusion example (XInclude C.1)
01352 
01353     >>> from xml.etree import ElementTree as ET
01354     >>> from xml.etree import ElementInclude
01355 
01356     >>> document = xinclude_loader("C1.xml")
01357     >>> ElementInclude.include(document, xinclude_loader)
01358     >>> print(serialize(document)) # C1
01359     <document>
01360       <p>120 Mz is adequate for an average home user.</p>
01361       <disclaimer>
01362       <p>The opinions represented herein represent those of the individual
01363       and should not be interpreted as official policy endorsed by this
01364       organization.</p>
01365     </disclaimer>
01366     </document>
01367 
01368     Textual inclusion example (XInclude C.2)
01369 
01370     >>> document = xinclude_loader("C2.xml")
01371     >>> ElementInclude.include(document, xinclude_loader)
01372     >>> print(serialize(document)) # C2
01373     <document>
01374       <p>This document has been accessed
01375       324387 times.</p>
01376     </document>
01377 
01378     Textual inclusion after sibling element (based on modified XInclude C.2)
01379 
01380     >>> document = xinclude_loader("C2b.xml")
01381     >>> ElementInclude.include(document, xinclude_loader)
01382     >>> print(serialize(document)) # C2b
01383     <document>
01384       <p>This document has been <em>accessed</em>
01385       324387 times.</p>
01386     </document>
01387 
01388     Textual inclusion of XML example (XInclude C.3)
01389 
01390     >>> document = xinclude_loader("C3.xml")
01391     >>> ElementInclude.include(document, xinclude_loader)
01392     >>> print(serialize(document)) # C3
01393     <document>
01394       <p>The following is the source of the "data.xml" resource:</p>
01395       <example>&lt;?xml version='1.0'?&gt;
01396     &lt;data&gt;
01397       &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;
01398     &lt;/data&gt;
01399     </example>
01400     </document>
01401 
01402     Fallback example (XInclude C.5)
01403     Note! Fallback support is not yet implemented
01404 
01405     >>> document = xinclude_loader("C5.xml")
01406     >>> ElementInclude.include(document, xinclude_loader)
01407     Traceback (most recent call last):
01408     IOError: resource not found
01409     >>> # print(serialize(document)) # C5
01410     """

>>> from xml.etree import ElementInclude

>>> document = xinclude_loader("default.xml")
>>> ElementInclude.include(document)
>>> print(serialize(document)) # default
<document>
  <p>Example.</p>
  <root>
   <element key="value">text</element>
   <element>text</element>tail
   <empty-element />
</root>
</document>

Definition at line 1411 of file test_xml_etree.py.

01411 
01412 def xinclude_default():
01413     """
01414     >>> from xml.etree import ElementInclude
01415 
01416     >>> document = xinclude_loader("default.xml")
01417     >>> ElementInclude.include(document)
01418     >>> print(serialize(document)) # default
01419     <document>
01420       <p>Example.</p>
01421       <root>
01422        <element key="value">text</element>
01423        <element>text</element>tail
01424        <empty-element />
01425     </root>
01426     </document>
01427     """
01428 
01429 #
01430 # badly formatted xi:include tags

\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>120 Mz is adequate for an average home user.</p>
  <xi:include href="disclaimer.xml" parse="BAD_TYPE"/>
</document>
\
<?xml version='1.0'?>
<div xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:fallback></xi:fallback>
</div>

Definition at line 1448 of file test_xml_etree.py.

01448 
01449 def xinclude_failures():
01450     r"""
01451     Test failure to locate included XML file.
01452 
01453     >>> from xml.etree import ElementInclude
01454 
01455     >>> def none_loader(href, parser, encoding=None):
01456     ...     return None
01457 
01458     >>> document = ET.XML(XINCLUDE["C1.xml"])
01459     >>> ElementInclude.include(document, loader=none_loader)
01460     Traceback (most recent call last):
01461     xml.etree.ElementInclude.FatalIncludeError: cannot load 'disclaimer.xml' as 'xml'
01462 
01463     Test failure to locate included text file.
01464 
01465     >>> document = ET.XML(XINCLUDE["C2.xml"])
01466     >>> ElementInclude.include(document, loader=none_loader)
01467     Traceback (most recent call last):
01468     xml.etree.ElementInclude.FatalIncludeError: cannot load 'count.txt' as 'text'
01469 
01470     Test bad parse type.
01471 
01472     >>> document = ET.XML(XINCLUDE_BAD["B1.xml"])
01473     >>> ElementInclude.include(document, loader=none_loader)
01474     Traceback (most recent call last):
01475     xml.etree.ElementInclude.FatalIncludeError: unknown parse type in xi:include tag ('BAD_TYPE')
01476 
01477     Test xi:fallback outside xi:include.
01478 
01479     >>> document = ET.XML(XINCLUDE_BAD["B2.xml"])
01480     >>> ElementInclude.include(document, loader=none_loader)
01481     Traceback (most recent call last):
01482     xml.etree.ElementInclude.FatalIncludeError: xi:fallback tag must be child of xi:include ('{http://www.w3.org/2001/XInclude}fallback')
01483     """
01484 
01485 # --------------------------------------------------------------------
01486 # reported bugs

def test.test_xml_etree.xinclude_loader (   href,
  parse = "xml",
  encoding = None 
)
\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>120 Mz is adequate for an average home user.</p>
  <xi:include href="disclaimer.xml"/>
</document>
\
<?xml version='1.0'?>
<disclaimer>
  <p>The opinions represented herein represent those of the individual
  and should not be interpreted as official policy endorsed by this
  organization.</p>
</disclaimer>
\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>This document has been accessed
  <xi:include href="count.txt" parse="text"/> times.</p>
</document>
\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>This document has been <em>accessed</em>
  <xi:include href="count.txt" parse="text"/> times.</p>
</document>
\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>The following is the source of the "data.xml" resource:</p>
  <example><xi:include href="data.xml" parse="text"/></example>
</document>
\
<?xml version='1.0'?>
<data>
  <item><![CDATA[Brooks & Shields]]></item>
</data>
\
<?xml version='1.0'?>
<div xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="example.txt" parse="text">
<xi:fallback>
  <xi:include href="fallback-example.txt" parse="text">
    <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback>
  </xi:include>
</xi:fallback>
  </xi:include>
</div>
\
<?xml version='1.0'?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <p>Example.</p>
  <xi:include href="{}"/>
</document>

Definition at line 1338 of file test_xml_etree.py.

01338 
01339 def xinclude_loader(href, parse="xml", encoding=None):
01340     try:
01341         data = XINCLUDE[href]
01342     except KeyError:
01343         raise IOError("resource not found")
01344     if parse == "xml":
01345         from xml.etree.ElementTree import XML
01346         return XML(data)
01347     return data

Here is the call graph for this function:

Handle crash in stream source.
>>> tree = ET.parse(ExceptionFile())
Traceback (most recent call last):
IOError

Definition at line 1616 of file test_xml_etree.py.

01616 
01617 def xmltoolkit60():
01618     """
01619 
01620     Handle crash in stream source.
01621     >>> tree = ET.parse(ExceptionFile())
01622     Traceback (most recent call last):
01623     IOError
01624 
01625     """

Don't crash when using custom entities.

>>> xmltoolkit62()
'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.'

Definition at line 1635 of file test_xml_etree.py.

01635 
01636 def xmltoolkit62():
01637     """
01638 
01639     Don't crash when using custom entities.
01640 
01641     >>> xmltoolkit62()
01642     'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.'
01643 
01644     """
01645     ENTITIES = {'rsquo': '\u2019', 'lsquo': '\u2018'}
01646     parser = ET.XMLTreeBuilder()
01647     parser.entity.update(ENTITIES)
01648     parser.feed(XMLTOOLKIT62_DOC)
01649     t = parser.close()
01650     return t.find('.//paragraph').text

Check reference leak.
>>> xmltoolkit63()
>>> count = sys.getrefcount(None)
>>> for i in range(1000):
...     xmltoolkit63()
>>> sys.getrefcount(None) - count
0

Definition at line 1651 of file test_xml_etree.py.

01651 
01652 def xmltoolkit63():
01653     """
01654 
01655     Check reference leak.
01656     >>> xmltoolkit63()
01657     >>> count = sys.getrefcount(None)
01658     >>> for i in range(1000):
01659     ...     xmltoolkit63()
01660     >>> sys.getrefcount(None) - count
01661     0
01662 
01663     """
01664     tree = ET.TreeBuilder()
01665     tree.start("tag", {})
01666     tree.data("text")
01667     tree.end("tag")
01668 
01669 # --------------------------------------------------------------------
01670 

Test the XPath tokenizer.

>>> # tests from the xml specification
>>> xpath_tokenizer("*")
['*']
>>> xpath_tokenizer("text()")
['text', '()']
>>> xpath_tokenizer("@name")
['@', 'name']
>>> xpath_tokenizer("@*")
['@', '*']
>>> xpath_tokenizer("para[1]")
['para', '[', '1', ']']
>>> xpath_tokenizer("para[last()]")
['para', '[', 'last', '()', ']']
>>> xpath_tokenizer("*/para")
['*', '/', 'para']
>>> xpath_tokenizer("/doc/chapter[5]/section[2]")
['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']
>>> xpath_tokenizer("chapter//para")
['chapter', '//', 'para']
>>> xpath_tokenizer("//para")
['//', 'para']
>>> xpath_tokenizer("//olist/item")
['//', 'olist', '/', 'item']
>>> xpath_tokenizer(".")
['.']
>>> xpath_tokenizer(".//para")
['.', '//', 'para']
>>> xpath_tokenizer("..")
['..']
>>> xpath_tokenizer("../@lang")
['..', '/', '@', 'lang']
>>> xpath_tokenizer("chapter[title]")
['chapter', '[', 'title', ']']
>>> xpath_tokenizer("employee[@secretary and @assistant]")
['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']

>>> # additional tests
>>> xpath_tokenizer("{http://spam}egg")
['{http://spam}egg']
>>> xpath_tokenizer("./spam.egg")
['.', '/', 'spam.egg']
>>> xpath_tokenizer(".//{http://spam}egg")
['.', '//', '{http://spam}egg']

Definition at line 1191 of file test_xml_etree.py.

01191 
01192 def xpath_tokenizer(p):
01193     """
01194     Test the XPath tokenizer.
01195 
01196     >>> # tests from the xml specification
01197     >>> xpath_tokenizer("*")
01198     ['*']
01199     >>> xpath_tokenizer("text()")
01200     ['text', '()']
01201     >>> xpath_tokenizer("@name")
01202     ['@', 'name']
01203     >>> xpath_tokenizer("@*")
01204     ['@', '*']
01205     >>> xpath_tokenizer("para[1]")
01206     ['para', '[', '1', ']']
01207     >>> xpath_tokenizer("para[last()]")
01208     ['para', '[', 'last', '()', ']']
01209     >>> xpath_tokenizer("*/para")
01210     ['*', '/', 'para']
01211     >>> xpath_tokenizer("/doc/chapter[5]/section[2]")
01212     ['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']
01213     >>> xpath_tokenizer("chapter//para")
01214     ['chapter', '//', 'para']
01215     >>> xpath_tokenizer("//para")
01216     ['//', 'para']
01217     >>> xpath_tokenizer("//olist/item")
01218     ['//', 'olist', '/', 'item']
01219     >>> xpath_tokenizer(".")
01220     ['.']
01221     >>> xpath_tokenizer(".//para")
01222     ['.', '//', 'para']
01223     >>> xpath_tokenizer("..")
01224     ['..']
01225     >>> xpath_tokenizer("../@lang")
01226     ['..', '/', '@', 'lang']
01227     >>> xpath_tokenizer("chapter[title]")
01228     ['chapter', '[', 'title', ']']
01229     >>> xpath_tokenizer("employee[@secretary and @assistant]")
01230     ['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']
01231 
01232     >>> # additional tests
01233     >>> xpath_tokenizer("{http://spam}egg")
01234     ['{http://spam}egg']
01235     >>> xpath_tokenizer("./spam.egg")
01236     ['.', '/', 'spam.egg']
01237     >>> xpath_tokenizer(".//{http://spam}egg")
01238     ['.', '//', '{http://spam}egg']
01239     """
01240     from xml.etree import ElementPath
01241     out = []
01242     for op, tag in ElementPath.xpath_tokenizer(p):
01243         out.append(op or tag)
01244     return out


Variable Documentation

Initial value:
00001 """\
00002 <!DOCTYPE points [
00003 <!ENTITY % user-entities SYSTEM 'user-entities.xml'>
00004 %user-entities;
00005 ]>
00006 <document>&entity;</document>
00007 """

Definition at line 1011 of file test_xml_etree.py.

Initial value:
00001 """\
00002 <section>
00003   <tag class='b' id='inner'>subtext</tag>
00004   <nexttag />
00005   <nextsection>
00006     <tag />
00007   </nextsection>
00008 </section>
00009 """

Definition at line 40 of file test_xml_etree.py.

Initial value:
00001 """\
00002 <body>
00003   <tag class='a'>text</tag>
00004   <tag class='b' />
00005   <section>
00006     <tag class='b' id='inner'>subtext</tag>
00007   </section>
00008 </body>
00009 """

Definition at line 30 of file test_xml_etree.py.

Initial value:
00001 """
00002 <body xmlns="http://effbot.org/ns">
00003   <tag>text</tag>
00004   <tag />
00005   <section>
00006     <tag>subtext</tag>
00007   </section>
00008 </body>
00009 """

Definition at line 50 of file test_xml_etree.py.

tuple test.test_xml_etree.SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata")

Definition at line 28 of file test_xml_etree.py.

tuple test.test_xml_etree.SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata")

Definition at line 23 of file test_xml_etree.py.

Definition at line 1265 of file test_xml_etree.py.

Definition at line 1431 of file test_xml_etree.py.

Initial value:
00001 """<?xml version="1.0" encoding="UTF-8"?>
00002 <!DOCTYPE patent-application-publication SYSTEM "pap-v15-2001-01-31.dtd" []>
00003 <patent-application-publication>
00004 <subdoc-abstract>
00005 <paragraph id="A-0001" lvl="0">A new cultivar of Begonia plant named &lsquo;BCT9801BEG&rsquo;.</paragraph>
00006 </subdoc-abstract>
00007 </patent-application-publication>"""

Definition at line 1626 of file test_xml_etree.py.