]> granicus.if.org Git - python/commitdiff
Subversion settings:
authorArmin Rigo <arigo@tunes.org>
Wed, 14 Dec 2005 18:10:45 +0000 (18:10 +0000)
committerArmin Rigo <arigo@tunes.org>
Wed, 14 Dec 2005 18:10:45 +0000 (18:10 +0000)
  svn:ignore *.pyc *.pyo
  svn:eol-style native

The .py files appear to have been checked in with Windows or inconsistent line
endings.  The current check-in disrupts the 'svn blame', but hopefully it is
irrelevant for freshly imported code.

Lib/test/test_xml_etree.py
Lib/xmlcore/etree/ElementInclude.py
Lib/xmlcore/etree/ElementPath.py
Lib/xmlcore/etree/ElementTree.py
Lib/xmlcore/etree/__init__.py

index 94f6b31d9bb95e4b7e04bd5fec9c832391f94d2f..8692b41e57026e8be3becd4d6a2241ad099061f4 100644 (file)
-# xmlcore.etree test.  This file contains enough tests to make sure that\r
-# all included components work as they should.  For a more extensive\r
-# test suite, see the selftest script in the ElementTree distribution.\r
-\r
-import doctest, sys\r
-\r
-from test import test_support\r
-\r
-SAMPLE_XML = """\r
-<body>\r
-  <tag>text</tag>\r
-  <tag />\r
-  <section>\r
-    <tag>subtext</tag>\r
-  </section>\r
-</body>\r
-"""\r
-\r
-SAMPLE_XML_NS = """\r
-<body xmlns="http://effbot.org/ns">\r
-  <tag>text</tag>\r
-  <tag />\r
-  <section>\r
-    <tag>subtext</tag>\r
-  </section>\r
-</body>\r
-"""\r
-\r
-def sanity():\r
-    """\r
-    Import sanity.\r
-\r
-    >>> from xmlcore.etree import ElementTree\r
-    >>> from xmlcore.etree import ElementInclude\r
-    >>> from xmlcore.etree import ElementPath\r
-    """\r
-\r
-def check_method(method):\r
-    if not callable(method):\r
-        print method, "not callable"\r
-\r
-def serialize(ET, elem, encoding=None):\r
-    import StringIO\r
-    file = StringIO.StringIO()\r
-    tree = ET.ElementTree(elem)\r
-    if encoding:\r
-        tree.write(file, encoding)\r
-    else:\r
-        tree.write(file)\r
-    return file.getvalue()\r
-\r
-def summarize(elem):\r
-    return elem.tag\r
-\r
-def summarize_list(seq):\r
-    return map(summarize, seq)\r
-\r
-def interface():\r
-    """\r
-    Test element tree interface.\r
-\r
-    >>> from xmlcore.etree import ElementTree as ET\r
-\r
-    >>> element = ET.Element("tag", key="value")\r
-    >>> tree = ET.ElementTree(element)\r
-\r
-    Make sure all standard element methods exist.\r
-\r
-    >>> check_method(element.append)\r
-    >>> check_method(element.insert)\r
-    >>> check_method(element.remove)\r
-    >>> check_method(element.getchildren)\r
-    >>> check_method(element.find)\r
-    >>> check_method(element.findall)\r
-    >>> check_method(element.findtext)\r
-    >>> check_method(element.clear)\r
-    >>> check_method(element.get)\r
-    >>> check_method(element.set)\r
-    >>> check_method(element.keys)\r
-    >>> check_method(element.items)\r
-    >>> check_method(element.getiterator)\r
-\r
-    Basic method sanity checks.\r
-\r
-    >>> serialize(ET, element) # 1\r
-    '<tag key="value" />'\r
-    >>> subelement = ET.Element("subtag")\r
-    >>> element.append(subelement)\r
-    >>> serialize(ET, element) #  2\r
-    '<tag key="value"><subtag /></tag>'\r
-    >>> element.insert(0, subelement)\r
-    >>> serialize(ET, element) # 3\r
-    '<tag key="value"><subtag /><subtag /></tag>'\r
-    >>> element.remove(subelement)\r
-    >>> serialize(ET, element) # 4\r
-    '<tag key="value"><subtag /></tag>'\r
-    >>> element.remove(subelement)\r
-    >>> serialize(ET, element) # 5\r
-    '<tag key="value" />'\r
-    >>> element.remove(subelement)\r
-    Traceback (most recent call last):\r
-    ValueError: list.remove(x): x not in list\r
-    >>> serialize(ET, element) # 6\r
-    '<tag key="value" />'\r
-    """\r
-\r
-def find():\r
-    """\r
-    Test find methods (including xpath syntax).\r
-\r
-    >>> from xmlcore.etree import ElementTree as ET\r
-\r
-    >>> elem = ET.XML(SAMPLE_XML)\r
-    >>> elem.find("tag").tag\r
-    'tag'\r
-    >>> ET.ElementTree(elem).find("tag").tag\r
-    'tag'\r
-    >>> elem.find("section/tag").tag\r
-    'tag'\r
-    >>> ET.ElementTree(elem).find("section/tag").tag\r
-    'tag'\r
-    >>> elem.findtext("tag")\r
-    'text'\r
-    >>> elem.findtext("tog")\r
-    >>> elem.findtext("tog", "default")\r
-    'default'\r
-    >>> ET.ElementTree(elem).findtext("tag")\r
-    'text'\r
-    >>> elem.findtext("section/tag")\r
-    'subtext'\r
-    >>> ET.ElementTree(elem).findtext("section/tag")\r
-    'subtext'\r
-    >>> summarize_list(elem.findall("tag"))\r
-    ['tag', 'tag']\r
-    >>> summarize_list(elem.findall("*"))\r
-    ['tag', 'tag', 'section']\r
-    >>> summarize_list(elem.findall(".//tag"))\r
-    ['tag', 'tag', 'tag']\r
-    >>> summarize_list(elem.findall("section/tag"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("section//tag"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("section/*"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("section//*"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("section/.//*"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("*/*"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("*//*"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("*/tag"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("*/./tag"))\r
-    ['tag']\r
-    >>> summarize_list(elem.findall("./tag"))\r
-    ['tag', 'tag']\r
-    >>> summarize_list(elem.findall(".//tag"))\r
-    ['tag', 'tag', 'tag']\r
-    >>> summarize_list(elem.findall("././tag"))\r
-    ['tag', 'tag']\r
-    >>> summarize_list(ET.ElementTree(elem).findall("/tag"))\r
-    ['tag', 'tag']\r
-    >>> summarize_list(ET.ElementTree(elem).findall("./tag"))\r
-    ['tag', 'tag']\r
-    >>> elem = ET.XML(SAMPLE_XML_NS)\r
-    >>> summarize_list(elem.findall("tag"))\r
-    []\r
-    >>> summarize_list(elem.findall("{http://effbot.org/ns}tag"))\r
-    ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']\r
-    >>> summarize_list(elem.findall(".//{http://effbot.org/ns}tag"))\r
-    ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag']\r
-    """\r
-\r
-def parseliteral():\r
-    r"""\r
-\r
-    >>> from xmlcore.etree import ElementTree as ET\r
-\r
-    >>> element = ET.XML("<html><body>text</body></html>")\r
-    >>> ET.ElementTree(element).write(sys.stdout)\r
-    <html><body>text</body></html>\r
-    >>> element = ET.fromstring("<html><body>text</body></html>")\r
-    >>> ET.ElementTree(element).write(sys.stdout)\r
-    <html><body>text</body></html>\r
-    >>> print ET.tostring(element)\r
-    <html><body>text</body></html>\r
-    >>> print ET.tostring(element, "ascii")\r
-    <?xml version='1.0' encoding='ascii'?>\r
-    <html><body>text</body></html>\r
-    >>> _, ids = ET.XMLID("<html><body>text</body></html>")\r
-    >>> len(ids)\r
-    0\r
-    >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")\r
-    >>> len(ids)\r
-    1\r
-    >>> ids["body"].tag\r
-    'body'\r
-    """\r
-\r
-#\r
-# xinclude tests (samples from appendix C of the xinclude specification)\r
-\r
-XINCLUDE = {}\r
-\r
-XINCLUDE["C1.xml"] = """\\r
-<?xml version='1.0'?>\r
-<document xmlns:xi="http://www.w3.org/2001/XInclude">\r
-  <p>120 Mz is adequate for an average home user.</p>\r
-  <xi:include href="disclaimer.xml"/>\r
-</document>\r
-"""\r
-\r
-XINCLUDE["disclaimer.xml"] = """\\r
-<?xml version='1.0'?>\r
-<disclaimer>\r
-  <p>The opinions represented herein represent those of the individual\r
-  and should not be interpreted as official policy endorsed by this\r
-  organization.</p>\r
-</disclaimer>\r
-"""\r
-\r
-XINCLUDE["C2.xml"] = """\\r
-<?xml version='1.0'?>\r
-<document xmlns:xi="http://www.w3.org/2001/XInclude">\r
-  <p>This document has been accessed\r
-  <xi:include href="count.txt" parse="text"/> times.</p>\r
-</document>\r
-"""\r
-\r
-XINCLUDE["count.txt"] = "324387"\r
-\r
-XINCLUDE["C3.xml"] = """\\r
-<?xml version='1.0'?>\r
-<document xmlns:xi="http://www.w3.org/2001/XInclude">\r
-  <p>The following is the source of the "data.xml" resource:</p>\r
-  <example><xi:include href="data.xml" parse="text"/></example>\r
-</document>\r
-"""\r
-\r
-XINCLUDE["data.xml"] = """\\r
-<?xml version='1.0'?>\r
-<data>\r
-  <item><![CDATA[Brooks & Shields]]></item>\r
-</data>\r
-"""\r
-\r
-XINCLUDE["C5.xml"] = """\\r
-<?xml version='1.0'?>\r
-<div xmlns:xi="http://www.w3.org/2001/XInclude">\r
-  <xi:include href="example.txt" parse="text">\r
-    <xi:fallback>\r
-      <xi:include href="fallback-example.txt" parse="text">\r
-        <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback>\r
-      </xi:include>\r
-    </xi:fallback>\r
-  </xi:include>\r
-</div>\r
-"""\r
-\r
-XINCLUDE["default.xml"] = """\\r
-<?xml version='1.0'?>\r
-<document xmlns:xi="http://www.w3.org/2001/XInclude">\r
-  <p>Example.</p>\r
-  <xi:include href="samples/simple.xml"/>\r
-</document>\r
-"""\r
-\r
-def xinclude_loader(href, parse="xml", encoding=None):\r
-    try:\r
-        data = XINCLUDE[href]\r
-    except KeyError:\r
-        raise IOError("resource not found")\r
-    if parse == "xml":\r
-        from xmlcore.etree.ElementTree import XML\r
-        return XML(data)\r
-    return data\r
-\r
-def xinclude():\r
-    r"""\r
-    Basic inclusion example (XInclude C.1)\r
-\r
-    >>> from xmlcore.etree import ElementTree as ET\r
-    >>> from xmlcore.etree import ElementInclude\r
-\r
-    >>> document = xinclude_loader("C1.xml")\r
-    >>> ElementInclude.include(document, xinclude_loader)\r
-    >>> print serialize(ET, document) # C1\r
-    <document>\r
-      <p>120 Mz is adequate for an average home user.</p>\r
-      <disclaimer>\r
-      <p>The opinions represented herein represent those of the individual\r
-      and should not be interpreted as official policy endorsed by this\r
-      organization.</p>\r
-    </disclaimer>\r
-    </document>\r
-\r
-    Textual inclusion example (XInclude C.2)\r
-\r
-    >>> document = xinclude_loader("C2.xml")\r
-    >>> ElementInclude.include(document, xinclude_loader)\r
-    >>> print serialize(ET, document) # C2\r
-    <document>\r
-      <p>This document has been accessed\r
-      324387 times.</p>\r
-    </document>\r
-\r
-    Textual inclusion of XML example (XInclude C.3)\r
-\r
-    >>> document = xinclude_loader("C3.xml")\r
-    >>> ElementInclude.include(document, xinclude_loader)\r
-    >>> print serialize(ET, document) # C3\r
-    <document>\r
-      <p>The following is the source of the "data.xml" resource:</p>\r
-      <example>&lt;?xml version='1.0'?&gt;\r
-    &lt;data&gt;\r
-      &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;\r
-    &lt;/data&gt;\r
-    </example>\r
-    </document>\r
-\r
-    Fallback example (XInclude C.5)\r
-    Note! Fallback support is not yet implemented\r
-\r
-    >>> document = xinclude_loader("C5.xml")\r
-    >>> ElementInclude.include(document, xinclude_loader)\r
-    Traceback (most recent call last):\r
-    IOError: resource not found\r
-    >>> # print serialize(ET, document) # C5\r
-\r
-    """\r
-\r
-def test_main():\r
-    from test import test_xml_etree\r
-    test_support.run_doctest(test_xml_etree, verbosity=True)\r
-\r
-if __name__ == '__main__':\r
-    test_main()\r
+# xmlcore.etree test.  This file contains enough tests to make sure that
+# all included components work as they should.  For a more extensive
+# test suite, see the selftest script in the ElementTree distribution.
+
+import doctest, sys
+
+from test import test_support
+
+SAMPLE_XML = """
+<body>
+  <tag>text</tag>
+  <tag />
+  <section>
+    <tag>subtext</tag>
+  </section>
+</body>
+"""
+
+SAMPLE_XML_NS = """
+<body xmlns="http://effbot.org/ns">
+  <tag>text</tag>
+  <tag />
+  <section>
+    <tag>subtext</tag>
+  </section>
+</body>
+"""
+
+def sanity():
+    """
+    Import sanity.
+
+    >>> from xmlcore.etree import ElementTree
+    >>> from xmlcore.etree import ElementInclude
+    >>> from xmlcore.etree import ElementPath
+    """
+
+def check_method(method):
+    if not callable(method):
+        print method, "not callable"
+
+def serialize(ET, elem, encoding=None):
+    import StringIO
+    file = StringIO.StringIO()
+    tree = ET.ElementTree(elem)
+    if encoding:
+        tree.write(file, encoding)
+    else:
+        tree.write(file)
+    return file.getvalue()
+
+def summarize(elem):
+    return elem.tag
+
+def summarize_list(seq):
+    return map(summarize, seq)
+
+def interface():
+    """
+    Test element tree interface.
+
+    >>> from xmlcore.etree import ElementTree as ET
+
+    >>> element = ET.Element("tag", key="value")
+    >>> tree = ET.ElementTree(element)
+
+    Make sure all standard element methods exist.
+
+    >>> check_method(element.append)
+    >>> check_method(element.insert)
+    >>> check_method(element.remove)
+    >>> check_method(element.getchildren)
+    >>> check_method(element.find)
+    >>> 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.getiterator)
+
+    Basic method sanity checks.
+
+    >>> serialize(ET, element) # 1
+    '<tag key="value" />'
+    >>> subelement = ET.Element("subtag")
+    >>> element.append(subelement)
+    >>> serialize(ET, element) #  2
+    '<tag key="value"><subtag /></tag>'
+    >>> element.insert(0, subelement)
+    >>> serialize(ET, element) # 3
+    '<tag key="value"><subtag /><subtag /></tag>'
+    >>> element.remove(subelement)
+    >>> serialize(ET, element) # 4
+    '<tag key="value"><subtag /></tag>'
+    >>> element.remove(subelement)
+    >>> serialize(ET, element) # 5
+    '<tag key="value" />'
+    >>> element.remove(subelement)
+    Traceback (most recent call last):
+    ValueError: list.remove(x): x not in list
+    >>> serialize(ET, element) # 6
+    '<tag key="value" />'
+    """
+
+def find():
+    """
+    Test find methods (including xpath syntax).
+
+    >>> from xmlcore.etree import ElementTree as ET
+
+    >>> elem = ET.XML(SAMPLE_XML)
+    >>> elem.find("tag").tag
+    'tag'
+    >>> ET.ElementTree(elem).find("tag").tag
+    'tag'
+    >>> elem.find("section/tag").tag
+    'tag'
+    >>> ET.ElementTree(elem).find("section/tag").tag
+    'tag'
+    >>> elem.findtext("tag")
+    'text'
+    >>> elem.findtext("tog")
+    >>> elem.findtext("tog", "default")
+    'default'
+    >>> ET.ElementTree(elem).findtext("tag")
+    'text'
+    >>> elem.findtext("section/tag")
+    'subtext'
+    >>> ET.ElementTree(elem).findtext("section/tag")
+    'subtext'
+    >>> summarize_list(elem.findall("tag"))
+    ['tag', 'tag']
+    >>> summarize_list(elem.findall("*"))
+    ['tag', 'tag', 'section']
+    >>> summarize_list(elem.findall(".//tag"))
+    ['tag', 'tag', 'tag']
+    >>> summarize_list(elem.findall("section/tag"))
+    ['tag']
+    >>> summarize_list(elem.findall("section//tag"))
+    ['tag']
+    >>> summarize_list(elem.findall("section/*"))
+    ['tag']
+    >>> summarize_list(elem.findall("section//*"))
+    ['tag']
+    >>> summarize_list(elem.findall("section/.//*"))
+    ['tag']
+    >>> summarize_list(elem.findall("*/*"))
+    ['tag']
+    >>> summarize_list(elem.findall("*//*"))
+    ['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']
+    >>> summarize_list(elem.findall("././tag"))
+    ['tag', 'tag']
+    >>> summarize_list(ET.ElementTree(elem).findall("/tag"))
+    ['tag', 'tag']
+    >>> 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']
+    """
+
+def parseliteral():
+    r"""
+
+    >>> from xmlcore.etree import ElementTree as ET
+
+    >>> element = ET.XML("<html><body>text</body></html>")
+    >>> ET.ElementTree(element).write(sys.stdout)
+    <html><body>text</body></html>
+    >>> element = ET.fromstring("<html><body>text</body></html>")
+    >>> ET.ElementTree(element).write(sys.stdout)
+    <html><body>text</body></html>
+    >>> print ET.tostring(element)
+    <html><body>text</body></html>
+    >>> print ET.tostring(element, "ascii")
+    <?xml version='1.0' encoding='ascii'?>
+    <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'
+    """
+
+#
+# xinclude tests (samples from appendix C of the xinclude specification)
+
+XINCLUDE = {}
+
+XINCLUDE["C1.xml"] = """\
+<?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>
+"""
+
+XINCLUDE["disclaimer.xml"] = """\
+<?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>
+"""
+
+XINCLUDE["C2.xml"] = """\
+<?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>
+"""
+
+XINCLUDE["count.txt"] = "324387"
+
+XINCLUDE["C3.xml"] = """\
+<?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>
+"""
+
+XINCLUDE["data.xml"] = """\
+<?xml version='1.0'?>
+<data>
+  <item><![CDATA[Brooks & Shields]]></item>
+</data>
+"""
+
+XINCLUDE["C5.xml"] = """\
+<?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>
+"""
+
+XINCLUDE["default.xml"] = """\
+<?xml version='1.0'?>
+<document xmlns:xi="http://www.w3.org/2001/XInclude">
+  <p>Example.</p>
+  <xi:include href="samples/simple.xml"/>
+</document>
+"""
+
+def xinclude_loader(href, parse="xml", encoding=None):
+    try:
+        data = XINCLUDE[href]
+    except KeyError:
+        raise IOError("resource not found")
+    if parse == "xml":
+        from xmlcore.etree.ElementTree import XML
+        return XML(data)
+    return data
+
+def xinclude():
+    r"""
+    Basic inclusion example (XInclude C.1)
+
+    >>> from xmlcore.etree import ElementTree as ET
+    >>> from xmlcore.etree import ElementInclude
+
+    >>> document = xinclude_loader("C1.xml")
+    >>> ElementInclude.include(document, xinclude_loader)
+    >>> print serialize(ET, document) # C1
+    <document>
+      <p>120 Mz is adequate for an average home user.</p>
+      <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>
+    </document>
+
+    Textual inclusion example (XInclude C.2)
+
+    >>> document = xinclude_loader("C2.xml")
+    >>> ElementInclude.include(document, xinclude_loader)
+    >>> print serialize(ET, document) # C2
+    <document>
+      <p>This document has been accessed
+      324387 times.</p>
+    </document>
+
+    Textual inclusion of XML example (XInclude C.3)
+
+    >>> document = xinclude_loader("C3.xml")
+    >>> ElementInclude.include(document, xinclude_loader)
+    >>> print serialize(ET, document) # C3
+    <document>
+      <p>The following is the source of the "data.xml" resource:</p>
+      <example>&lt;?xml version='1.0'?&gt;
+    &lt;data&gt;
+      &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;
+    &lt;/data&gt;
+    </example>
+    </document>
+
+    Fallback example (XInclude C.5)
+    Note! Fallback support is not yet implemented
+
+    >>> document = xinclude_loader("C5.xml")
+    >>> ElementInclude.include(document, xinclude_loader)
+    Traceback (most recent call last):
+    IOError: resource not found
+    >>> # print serialize(ET, document) # C5
+
+    """
+
+def test_main():
+    from test import test_xml_etree
+    test_support.run_doctest(test_xml_etree, verbosity=True)
+
+if __name__ == '__main__':
+    test_main()
index 5ee199a141ed59fd5d4423127afa7978217c23e8..bac2f5e4e1016ca25457e9c630dfdf404760a509 100644 (file)
-#\r
-# ElementTree\r
-# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $\r
-#\r
-# limited xinclude support for element trees\r
-#\r
-# history:\r
-# 2003-08-15 fl   created\r
-# 2003-11-14 fl   fixed default loader\r
-#\r
-# Copyright (c) 2003-2004 by Fredrik Lundh.  All rights reserved.\r
-#\r
-# fredrik@pythonware.com\r
-# http://www.pythonware.com\r
-#\r
-# --------------------------------------------------------------------\r
-# The ElementTree toolkit is\r
-#\r
-# Copyright (c) 1999-2004 by Fredrik Lundh\r
-#\r
-# By obtaining, using, and/or copying this software and/or its\r
-# associated documentation, you agree that you have read, understood,\r
-# and will comply with the following terms and conditions:\r
-#\r
-# Permission to use, copy, modify, and distribute this software and\r
-# its associated documentation for any purpose and without fee is\r
-# hereby granted, provided that the above copyright notice appears in\r
-# all copies, and that both that copyright notice and this permission\r
-# notice appear in supporting documentation, and that the name of\r
-# Secret Labs AB or the author not be used in advertising or publicity\r
-# pertaining to distribution of the software without specific, written\r
-# prior permission.\r
-#\r
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\r
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\r
-# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\r
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\r
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\r
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\r
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\r
-# OF THIS SOFTWARE.\r
-# --------------------------------------------------------------------\r
-\r
-##\r
-# Limited XInclude support for the ElementTree package.\r
-##\r
-\r
-import copy\r
-import ElementTree\r
-\r
-XINCLUDE = "{http://www.w3.org/2001/XInclude}"\r
-\r
-XINCLUDE_INCLUDE = XINCLUDE + "include"\r
-XINCLUDE_FALLBACK = XINCLUDE + "fallback"\r
-\r
-##\r
-# Fatal include error.\r
-\r
-class FatalIncludeError(SyntaxError):\r
-    pass\r
-\r
-##\r
-# Default loader.  This loader reads an included resource from disk.\r
-#\r
-# @param href Resource reference.\r
-# @param parse Parse mode.  Either "xml" or "text".\r
-# @param encoding Optional text encoding.\r
-# @return The expanded resource.  If the parse mode is "xml", this\r
-#    is an ElementTree instance.  If the parse mode is "text", this\r
-#    is a Unicode string.  If the loader fails, it can return None\r
-#    or raise an IOError exception.\r
-# @throws IOError If the loader fails to load the resource.\r
-\r
-def default_loader(href, parse, encoding=None):\r
-    file = open(href)\r
-    if parse == "xml":\r
-        data = ElementTree.parse(file).getroot()\r
-    else:\r
-        data = file.read()\r
-        if encoding:\r
-            data = data.decode(encoding)\r
-    file.close()\r
-    return data\r
-\r
-##\r
-# Expand XInclude directives.\r
-#\r
-# @param elem Root element.\r
-# @param loader Optional resource loader.  If omitted, it defaults\r
-#     to {@link default_loader}.  If given, it should be a callable\r
-#     that implements the same interface as <b>default_loader</b>.\r
-# @throws FatalIncludeError If the function fails to include a given\r
-#     resource, or if the tree contains malformed XInclude elements.\r
-# @throws IOError If the function fails to load a given resource.\r
-\r
-def include(elem, loader=None):\r
-    if loader is None:\r
-        loader = default_loader\r
-    # look for xinclude elements\r
-    i = 0\r
-    while i < len(elem):\r
-        e = elem[i]\r
-        if e.tag == XINCLUDE_INCLUDE:\r
-            # process xinclude directive\r
-            href = e.get("href")\r
-            parse = e.get("parse", "xml")\r
-            if parse == "xml":\r
-                node = loader(href, parse)\r
-                if node is None:\r
-                    raise FatalIncludeError(\r
-                        "cannot load %r as %r" % (href, parse)\r
-                        )\r
-                node = copy.copy(node)\r
-                if e.tail:\r
-                    node.tail = (node.tail or "") + e.tail\r
-                elem[i] = node\r
-            elif parse == "text":\r
-                text = loader(href, parse, e.get("encoding"))\r
-                if text is None:\r
-                    raise FatalIncludeError(\r
-                        "cannot load %r as %r" % (href, parse)\r
-                        )\r
-                if i:\r
-                    node = elem[i-1]\r
-                    node.tail = (node.tail or "") + text\r
-                else:\r
-                    elem.text = (elem.text or "") + text + (e.tail or "")\r
-                del elem[i]\r
-                continue\r
-            else:\r
-                raise FatalIncludeError(\r
-                    "unknown parse type in xi:include tag (%r)" % parse\r
-                )\r
-        elif e.tag == XINCLUDE_FALLBACK:\r
-            raise FatalIncludeError(\r
-                "xi:fallback tag must be child of xi:include (%r)" % e.tag\r
-                )\r
-        else:\r
-            include(e, loader)\r
-        i = i + 1\r
-\r
+#
+# ElementTree
+# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $
+#
+# limited xinclude support for element trees
+#
+# history:
+# 2003-08-15 fl   created
+# 2003-11-14 fl   fixed default loader
+#
+# Copyright (c) 2003-2004 by Fredrik Lundh.  All rights reserved.
+#
+# fredrik@pythonware.com
+# http://www.pythonware.com
+#
+# --------------------------------------------------------------------
+# The ElementTree toolkit is
+#
+# Copyright (c) 1999-2004 by Fredrik Lundh
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------
+
+##
+# Limited XInclude support for the ElementTree package.
+##
+
+import copy
+import ElementTree
+
+XINCLUDE = "{http://www.w3.org/2001/XInclude}"
+
+XINCLUDE_INCLUDE = XINCLUDE + "include"
+XINCLUDE_FALLBACK = XINCLUDE + "fallback"
+
+##
+# Fatal include error.
+
+class FatalIncludeError(SyntaxError):
+    pass
+
+##
+# Default loader.  This loader reads an included resource from disk.
+#
+# @param href Resource reference.
+# @param parse Parse mode.  Either "xml" or "text".
+# @param encoding Optional text encoding.
+# @return The expanded resource.  If the parse mode is "xml", this
+#    is an ElementTree instance.  If the parse mode is "text", this
+#    is a Unicode string.  If the loader fails, it can return None
+#    or raise an IOError exception.
+# @throws IOError If the loader fails to load the resource.
+
+def default_loader(href, parse, encoding=None):
+    file = open(href)
+    if parse == "xml":
+        data = ElementTree.parse(file).getroot()
+    else:
+        data = file.read()
+        if encoding:
+            data = data.decode(encoding)
+    file.close()
+    return data
+
+##
+# Expand XInclude directives.
+#
+# @param elem Root element.
+# @param loader Optional resource loader.  If omitted, it defaults
+#     to {@link default_loader}.  If given, it should be a callable
+#     that implements the same interface as <b>default_loader</b>.
+# @throws FatalIncludeError If the function fails to include a given
+#     resource, or if the tree contains malformed XInclude elements.
+# @throws IOError If the function fails to load a given resource.
+
+def include(elem, loader=None):
+    if loader is None:
+        loader = default_loader
+    # look for xinclude elements
+    i = 0
+    while i < len(elem):
+        e = elem[i]
+        if e.tag == XINCLUDE_INCLUDE:
+            # process xinclude directive
+            href = e.get("href")
+            parse = e.get("parse", "xml")
+            if parse == "xml":
+                node = loader(href, parse)
+                if node is None:
+                    raise FatalIncludeError(
+                        "cannot load %r as %r" % (href, parse)
+                        )
+                node = copy.copy(node)
+                if e.tail:
+                    node.tail = (node.tail or "") + e.tail
+                elem[i] = node
+            elif parse == "text":
+                text = loader(href, parse, e.get("encoding"))
+                if text is None:
+                    raise FatalIncludeError(
+                        "cannot load %r as %r" % (href, parse)
+                        )
+                if i:
+                    node = elem[i-1]
+                    node.tail = (node.tail or "") + text
+                else:
+                    elem.text = (elem.text or "") + text + (e.tail or "")
+                del elem[i]
+                continue
+            else:
+                raise FatalIncludeError(
+                    "unknown parse type in xi:include tag (%r)" % parse
+                )
+        elif e.tag == XINCLUDE_FALLBACK:
+            raise FatalIncludeError(
+                "xi:fallback tag must be child of xi:include (%r)" % e.tag
+                )
+        else:
+            include(e, loader)
+        i = i + 1
+
index e8093c6010d6ae96ca84274e81cfcb69e15488ef..558b560affa1a5b21a42c4972ab55b953ed7ba11 100644 (file)
-#\r
-# ElementTree\r
-# $Id: ElementPath.py 1858 2004-06-17 21:31:41Z Fredrik $\r
-#\r
-# limited xpath support for element trees\r
-#\r
-# history:\r
-# 2003-05-23 fl   created\r
-# 2003-05-28 fl   added support for // etc\r
-# 2003-08-27 fl   fixed parsing of periods in element names\r
-#\r
-# Copyright (c) 2003-2004 by Fredrik Lundh.  All rights reserved.\r
-#\r
-# fredrik@pythonware.com\r
-# http://www.pythonware.com\r
-#\r
-# --------------------------------------------------------------------\r
-# The ElementTree toolkit is\r
-#\r
-# Copyright (c) 1999-2004 by Fredrik Lundh\r
-#\r
-# By obtaining, using, and/or copying this software and/or its\r
-# associated documentation, you agree that you have read, understood,\r
-# and will comply with the following terms and conditions:\r
-#\r
-# Permission to use, copy, modify, and distribute this software and\r
-# its associated documentation for any purpose and without fee is\r
-# hereby granted, provided that the above copyright notice appears in\r
-# all copies, and that both that copyright notice and this permission\r
-# notice appear in supporting documentation, and that the name of\r
-# Secret Labs AB or the author not be used in advertising or publicity\r
-# pertaining to distribution of the software without specific, written\r
-# prior permission.\r
-#\r
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\r
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\r
-# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\r
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\r
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\r
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\r
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\r
-# OF THIS SOFTWARE.\r
-# --------------------------------------------------------------------\r
-\r
-##\r
-# Implementation module for XPath support.  There's usually no reason\r
-# to import this module directly; the <b>ElementTree</b> does this for\r
-# you, if needed.\r
-##\r
-\r
-import re\r
-\r
-xpath_tokenizer = re.compile(\r
-    "(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+"\r
-    ).findall\r
-\r
-class xpath_descendant_or_self:\r
-    pass\r
-\r
-##\r
-# Wrapper for a compiled XPath.\r
-\r
-class Path:\r
-\r
-    ##\r
-    # Create an Path instance from an XPath expression.\r
-\r
-    def __init__(self, path):\r
-        tokens = xpath_tokenizer(path)\r
-        # the current version supports 'path/path'-style expressions only\r
-        self.path = []\r
-        self.tag = None\r
-        if tokens and tokens[0][0] == "/":\r
-            raise SyntaxError("cannot use absolute path on element")\r
-        while tokens:\r
-            op, tag = tokens.pop(0)\r
-            if tag or op == "*":\r
-                self.path.append(tag or op)\r
-            elif op == ".":\r
-                pass\r
-            elif op == "/":\r
-                self.path.append(xpath_descendant_or_self())\r
-                continue\r
-            else:\r
-                raise SyntaxError("unsupported path syntax (%s)" % op)\r
-            if tokens:\r
-                op, tag = tokens.pop(0)\r
-                if op != "/":\r
-                    raise SyntaxError(\r
-                        "expected path separator (%s)" % (op or tag)\r
-                        )\r
-        if self.path and isinstance(self.path[-1], xpath_descendant_or_self):\r
-            raise SyntaxError("path cannot end with //")\r
-        if len(self.path) == 1 and isinstance(self.path[0], type("")):\r
-            self.tag = self.path[0]\r
-\r
-    ##\r
-    # Find first matching object.\r
-\r
-    def find(self, element):\r
-        tag = self.tag\r
-        if tag is None:\r
-            nodeset = self.findall(element)\r
-            if not nodeset:\r
-                return None\r
-            return nodeset[0]\r
-        for elem in element:\r
-            if elem.tag == tag:\r
-                return elem\r
-        return None\r
-\r
-    ##\r
-    # Find text for first matching object.\r
-\r
-    def findtext(self, element, default=None):\r
-        tag = self.tag\r
-        if tag is None:\r
-            nodeset = self.findall(element)\r
-            if not nodeset:\r
-                return default\r
-            return nodeset[0].text or ""\r
-        for elem in element:\r
-            if elem.tag == tag:\r
-                return elem.text or ""\r
-        return default\r
-\r
-    ##\r
-    # Find all matching objects.\r
-\r
-    def findall(self, element):\r
-        nodeset = [element]\r
-        index = 0\r
-        while 1:\r
-            try:\r
-                path = self.path[index]\r
-                index = index + 1\r
-            except IndexError:\r
-                return nodeset\r
-            set = []\r
-            if isinstance(path, xpath_descendant_or_self):\r
-                try:\r
-                    tag = self.path[index]\r
-                    if not isinstance(tag, type("")):\r
-                        tag = None\r
-                    else:\r
-                        index = index + 1\r
-                except IndexError:\r
-                    tag = None # invalid path\r
-                for node in nodeset:\r
-                    new = list(node.getiterator(tag))\r
-                    if new and new[0] is node:\r
-                        set.extend(new[1:])\r
-                    else:\r
-                        set.extend(new)\r
-            else:\r
-                for node in nodeset:\r
-                    for node in node:\r
-                        if path == "*" or node.tag == path:\r
-                            set.append(node)\r
-            if not set:\r
-                return []\r
-            nodeset = set\r
-\r
-_cache = {}\r
-\r
-##\r
-# (Internal) Compile path.\r
-\r
-def _compile(path):\r
-    p = _cache.get(path)\r
-    if p is not None:\r
-        return p\r
-    p = Path(path)\r
-    if len(_cache) >= 100:\r
-        _cache.clear()\r
-    _cache[path] = p\r
-    return p\r
-\r
-##\r
-# Find first matching object.\r
-\r
-def find(element, path):\r
-    return _compile(path).find(element)\r
-\r
-##\r
-# Find text for first matching object.\r
-\r
-def findtext(element, path, default=None):\r
-    return _compile(path).findtext(element, default)\r
-\r
-##\r
-# Find all matching objects.\r
-\r
-def findall(element, path):\r
-    return _compile(path).findall(element)\r
-\r
+#
+# ElementTree
+# $Id: ElementPath.py 1858 2004-06-17 21:31:41Z Fredrik $
+#
+# limited xpath support for element trees
+#
+# history:
+# 2003-05-23 fl   created
+# 2003-05-28 fl   added support for // etc
+# 2003-08-27 fl   fixed parsing of periods in element names
+#
+# Copyright (c) 2003-2004 by Fredrik Lundh.  All rights reserved.
+#
+# fredrik@pythonware.com
+# http://www.pythonware.com
+#
+# --------------------------------------------------------------------
+# The ElementTree toolkit is
+#
+# Copyright (c) 1999-2004 by Fredrik Lundh
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------
+
+##
+# Implementation module for XPath support.  There's usually no reason
+# to import this module directly; the <b>ElementTree</b> does this for
+# you, if needed.
+##
+
+import re
+
+xpath_tokenizer = re.compile(
+    "(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+"
+    ).findall
+
+class xpath_descendant_or_self:
+    pass
+
+##
+# Wrapper for a compiled XPath.
+
+class Path:
+
+    ##
+    # Create an Path instance from an XPath expression.
+
+    def __init__(self, path):
+        tokens = xpath_tokenizer(path)
+        # the current version supports 'path/path'-style expressions only
+        self.path = []
+        self.tag = None
+        if tokens and tokens[0][0] == "/":
+            raise SyntaxError("cannot use absolute path on element")
+        while tokens:
+            op, tag = tokens.pop(0)
+            if tag or op == "*":
+                self.path.append(tag or op)
+            elif op == ".":
+                pass
+            elif op == "/":
+                self.path.append(xpath_descendant_or_self())
+                continue
+            else:
+                raise SyntaxError("unsupported path syntax (%s)" % op)
+            if tokens:
+                op, tag = tokens.pop(0)
+                if op != "/":
+                    raise SyntaxError(
+                        "expected path separator (%s)" % (op or tag)
+                        )
+        if self.path and isinstance(self.path[-1], xpath_descendant_or_self):
+            raise SyntaxError("path cannot end with //")
+        if len(self.path) == 1 and isinstance(self.path[0], type("")):
+            self.tag = self.path[0]
+
+    ##
+    # Find first matching object.
+
+    def find(self, element):
+        tag = self.tag
+        if tag is None:
+            nodeset = self.findall(element)
+            if not nodeset:
+                return None
+            return nodeset[0]
+        for elem in element:
+            if elem.tag == tag:
+                return elem
+        return None
+
+    ##
+    # Find text for first matching object.
+
+    def findtext(self, element, default=None):
+        tag = self.tag
+        if tag is None:
+            nodeset = self.findall(element)
+            if not nodeset:
+                return default
+            return nodeset[0].text or ""
+        for elem in element:
+            if elem.tag == tag:
+                return elem.text or ""
+        return default
+
+    ##
+    # Find all matching objects.
+
+    def findall(self, element):
+        nodeset = [element]
+        index = 0
+        while 1:
+            try:
+                path = self.path[index]
+                index = index + 1
+            except IndexError:
+                return nodeset
+            set = []
+            if isinstance(path, xpath_descendant_or_self):
+                try:
+                    tag = self.path[index]
+                    if not isinstance(tag, type("")):
+                        tag = None
+                    else:
+                        index = index + 1
+                except IndexError:
+                    tag = None # invalid path
+                for node in nodeset:
+                    new = list(node.getiterator(tag))
+                    if new and new[0] is node:
+                        set.extend(new[1:])
+                    else:
+                        set.extend(new)
+            else:
+                for node in nodeset:
+                    for node in node:
+                        if path == "*" or node.tag == path:
+                            set.append(node)
+            if not set:
+                return []
+            nodeset = set
+
+_cache = {}
+
+##
+# (Internal) Compile path.
+
+def _compile(path):
+    p = _cache.get(path)
+    if p is not None:
+        return p
+    p = Path(path)
+    if len(_cache) >= 100:
+        _cache.clear()
+    _cache[path] = p
+    return p
+
+##
+# Find first matching object.
+
+def find(element, path):
+    return _compile(path).find(element)
+
+##
+# Find text for first matching object.
+
+def findtext(element, path, default=None):
+    return _compile(path).findtext(element, default)
+
+##
+# Find all matching objects.
+
+def findall(element, path):
+    return _compile(path).findall(element)
+
index c18f7ff838e2edff6476e4809a840e8b29531f06..23c205838535e09a3584d067d7816174fa2afa91 100644 (file)
-#\r
-# ElementTree\r
-# $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $\r
-#\r
-# light-weight XML support for Python 1.5.2 and later.\r
-#\r
-# history:\r
-# 2001-10-20 fl   created (from various sources)\r
-# 2001-11-01 fl   return root from parse method\r
-# 2002-02-16 fl   sort attributes in lexical order\r
-# 2002-04-06 fl   TreeBuilder refactoring, added PythonDoc markup\r
-# 2002-05-01 fl   finished TreeBuilder refactoring\r
-# 2002-07-14 fl   added basic namespace support to ElementTree.write\r
-# 2002-07-25 fl   added QName attribute support\r
-# 2002-10-20 fl   fixed encoding in write\r
-# 2002-11-24 fl   changed default encoding to ascii; fixed attribute encoding\r
-# 2002-11-27 fl   accept file objects or file names for parse/write\r
-# 2002-12-04 fl   moved XMLTreeBuilder back to this module\r
-# 2003-01-11 fl   fixed entity encoding glitch for us-ascii\r
-# 2003-02-13 fl   added XML literal factory\r
-# 2003-02-21 fl   added ProcessingInstruction/PI factory\r
-# 2003-05-11 fl   added tostring/fromstring helpers\r
-# 2003-05-26 fl   added ElementPath support\r
-# 2003-07-05 fl   added makeelement factory method\r
-# 2003-07-28 fl   added more well-known namespace prefixes\r
-# 2003-08-15 fl   fixed typo in ElementTree.findtext (Thomas Dartsch)\r
-# 2003-09-04 fl   fall back on emulator if ElementPath is not installed\r
-# 2003-10-31 fl   markup updates\r
-# 2003-11-15 fl   fixed nested namespace bug\r
-# 2004-03-28 fl   added XMLID helper\r
-# 2004-06-02 fl   added default support to findtext\r
-# 2004-06-08 fl   fixed encoding of non-ascii element/attribute names\r
-# 2004-08-23 fl   take advantage of post-2.1 expat features\r
-# 2005-02-01 fl   added iterparse implementation\r
-# 2005-03-02 fl   fixed iterparse support for pre-2.2 versions\r
-#\r
-# Copyright (c) 1999-2005 by Fredrik Lundh.  All rights reserved.\r
-#\r
-# fredrik@pythonware.com\r
-# http://www.pythonware.com\r
-#\r
-# --------------------------------------------------------------------\r
-# The ElementTree toolkit is\r
-#\r
-# Copyright (c) 1999-2005 by Fredrik Lundh\r
-#\r
-# By obtaining, using, and/or copying this software and/or its\r
-# associated documentation, you agree that you have read, understood,\r
-# and will comply with the following terms and conditions:\r
-#\r
-# Permission to use, copy, modify, and distribute this software and\r
-# its associated documentation for any purpose and without fee is\r
-# hereby granted, provided that the above copyright notice appears in\r
-# all copies, and that both that copyright notice and this permission\r
-# notice appear in supporting documentation, and that the name of\r
-# Secret Labs AB or the author not be used in advertising or publicity\r
-# pertaining to distribution of the software without specific, written\r
-# prior permission.\r
-#\r
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\r
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\r
-# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\r
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\r
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\r
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\r
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\r
-# OF THIS SOFTWARE.\r
-# --------------------------------------------------------------------\r
-\r
-__all__ = [\r
-    # public symbols\r
-    "Comment",\r
-    "dump",\r
-    "Element", "ElementTree",\r
-    "fromstring",\r
-    "iselement", "iterparse",\r
-    "parse",\r
-    "PI", "ProcessingInstruction",\r
-    "QName",\r
-    "SubElement",\r
-    "tostring",\r
-    "TreeBuilder",\r
-    "VERSION", "XML",\r
-    "XMLTreeBuilder",\r
-    ]\r
-\r
-##\r
-# The <b>Element</b> type is a flexible container object, designed to\r
-# store hierarchical data structures in memory. The type can be\r
-# described as a cross between a list and a dictionary.\r
-# <p>\r
-# Each element has a number of properties associated with it:\r
-# <ul>\r
-# <li>a <i>tag</i>. This is a string identifying what kind of data\r
-# this element represents (the element type, in other words).</li>\r
-# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>\r
-# <li>a <i>text</i> string.</li>\r
-# <li>an optional <i>tail</i> string.</li>\r
-# <li>a number of <i>child elements</i>, stored in a Python sequence</li>\r
-# </ul>\r
-#\r
-# To create an element instance, use the {@link #Element} or {@link\r
-# #SubElement} factory functions.\r
-# <p>\r
-# The {@link #ElementTree} class can be used to wrap an element\r
-# structure, and convert it from and to XML.\r
-##\r
-\r
-import string, sys, re\r
-\r
-class _SimpleElementPath:\r
-    # emulate pre-1.2 find/findtext/findall behaviour\r
-    def find(self, element, tag):\r
-        for elem in element:\r
-            if elem.tag == tag:\r
-                return elem\r
-        return None\r
-    def findtext(self, element, tag, default=None):\r
-        for elem in element:\r
-            if elem.tag == tag:\r
-                return elem.text or ""\r
-        return default\r
-    def findall(self, element, tag):\r
-        if tag[:3] == ".//":\r
-            return element.getiterator(tag[3:])\r
-        result = []\r
-        for elem in element:\r
-            if elem.tag == tag:\r
-                result.append(elem)\r
-        return result\r
-\r
-try:\r
-    import ElementPath\r
-except ImportError:\r
-    # FIXME: issue warning in this case?\r
-    ElementPath = _SimpleElementPath()\r
-\r
-# TODO: add support for custom namespace resolvers/default namespaces\r
-# TODO: add improved support for incremental parsing\r
-\r
-VERSION = "1.2.6"\r
-\r
-##\r
-# Internal element class.  This class defines the Element interface,\r
-# and provides a reference implementation of this interface.\r
-# <p>\r
-# You should not create instances of this class directly.  Use the\r
-# appropriate factory functions instead, such as {@link #Element}\r
-# and {@link #SubElement}.\r
-#\r
-# @see Element\r
-# @see SubElement\r
-# @see Comment\r
-# @see ProcessingInstruction\r
-\r
-class _ElementInterface:\r
-    # <tag attrib>text<child/>...</tag>tail\r
-\r
-    ##\r
-    # (Attribute) Element tag.\r
-\r
-    tag = None\r
-\r
-    ##\r
-    # (Attribute) Element attribute dictionary.  Where possible, use\r
-    # {@link #_ElementInterface.get},\r
-    # {@link #_ElementInterface.set},\r
-    # {@link #_ElementInterface.keys}, and\r
-    # {@link #_ElementInterface.items} to access\r
-    # element attributes.\r
-\r
-    attrib = None\r
-\r
-    ##\r
-    # (Attribute) Text before first subelement.  This is either a\r
-    # string or the value None, if there was no text.\r
-\r
-    text = None\r
-\r
-    ##\r
-    # (Attribute) Text after this element's end tag, but before the\r
-    # next sibling element's start tag.  This is either a string or\r
-    # the value None, if there was no text.\r
-\r
-    tail = None # text after end tag, if any\r
-\r
-    def __init__(self, tag, attrib):\r
-        self.tag = tag\r
-        self.attrib = attrib\r
-        self._children = []\r
-\r
-    def __repr__(self):\r
-        return "<Element %s at %x>" % (self.tag, id(self))\r
-\r
-    ##\r
-    # Creates a new element object of the same type as this element.\r
-    #\r
-    # @param tag Element tag.\r
-    # @param attrib Element attributes, given as a dictionary.\r
-    # @return A new element instance.\r
-\r
-    def makeelement(self, tag, attrib):\r
-        return Element(tag, attrib)\r
-\r
-    ##\r
-    # Returns the number of subelements.\r
-    #\r
-    # @return The number of subelements.\r
-\r
-    def __len__(self):\r
-        return len(self._children)\r
-\r
-    ##\r
-    # Returns the given subelement.\r
-    #\r
-    # @param index What subelement to return.\r
-    # @return The given subelement.\r
-    # @exception IndexError If the given element does not exist.\r
-\r
-    def __getitem__(self, index):\r
-        return self._children[index]\r
-\r
-    ##\r
-    # Replaces the given subelement.\r
-    #\r
-    # @param index What subelement to replace.\r
-    # @param element The new element value.\r
-    # @exception IndexError If the given element does not exist.\r
-    # @exception AssertionError If element is not a valid object.\r
-\r
-    def __setitem__(self, index, element):\r
-        assert iselement(element)\r
-        self._children[index] = element\r
-\r
-    ##\r
-    # Deletes the given subelement.\r
-    #\r
-    # @param index What subelement to delete.\r
-    # @exception IndexError If the given element does not exist.\r
-\r
-    def __delitem__(self, index):\r
-        del self._children[index]\r
-\r
-    ##\r
-    # Returns a list containing subelements in the given range.\r
-    #\r
-    # @param start The first subelement to return.\r
-    # @param stop The first subelement that shouldn't be returned.\r
-    # @return A sequence object containing subelements.\r
-\r
-    def __getslice__(self, start, stop):\r
-        return self._children[start:stop]\r
-\r
-    ##\r
-    # Replaces a number of subelements with elements from a sequence.\r
-    #\r
-    # @param start The first subelement to replace.\r
-    # @param stop The first subelement that shouldn't be replaced.\r
-    # @param elements A sequence object with zero or more elements.\r
-    # @exception AssertionError If a sequence member is not a valid object.\r
-\r
-    def __setslice__(self, start, stop, elements):\r
-        for element in elements:\r
-            assert iselement(element)\r
-        self._children[start:stop] = list(elements)\r
-\r
-    ##\r
-    # Deletes a number of subelements.\r
-    #\r
-    # @param start The first subelement to delete.\r
-    # @param stop The first subelement to leave in there.\r
-\r
-    def __delslice__(self, start, stop):\r
-        del self._children[start:stop]\r
-\r
-    ##\r
-    # Adds a subelement to the end of this element.\r
-    #\r
-    # @param element The element to add.\r
-    # @exception AssertionError If a sequence member is not a valid object.\r
-\r
-    def append(self, element):\r
-        assert iselement(element)\r
-        self._children.append(element)\r
-\r
-    ##\r
-    # Inserts a subelement at the given position in this element.\r
-    #\r
-    # @param index Where to insert the new subelement.\r
-    # @exception AssertionError If the element is not a valid object.\r
-\r
-    def insert(self, index, element):\r
-        assert iselement(element)\r
-        self._children.insert(index, element)\r
-\r
-    ##\r
-    # Removes a matching subelement.  Unlike the <b>find</b> methods,\r
-    # this method compares elements based on identity, not on tag\r
-    # value or contents.\r
-    #\r
-    # @param element What element to remove.\r
-    # @exception ValueError If a matching element could not be found.\r
-    # @exception AssertionError If the element is not a valid object.\r
-\r
-    def remove(self, element):\r
-        assert iselement(element)\r
-        self._children.remove(element)\r
-\r
-    ##\r
-    # Returns all subelements.  The elements are returned in document\r
-    # order.\r
-    #\r
-    # @return A list of subelements.\r
-    # @defreturn list of Element instances\r
-\r
-    def getchildren(self):\r
-        return self._children\r
-\r
-    ##\r
-    # Finds the first matching subelement, by tag name or path.\r
-    #\r
-    # @param path What element to look for.\r
-    # @return The first matching element, or None if no element was found.\r
-    # @defreturn Element or None\r
-\r
-    def find(self, path):\r
-        return ElementPath.find(self, path)\r
-\r
-    ##\r
-    # Finds text for the first matching subelement, by tag name or path.\r
-    #\r
-    # @param path What element to look for.\r
-    # @param default What to return if the element was not found.\r
-    # @return The text content of the first matching element, or the\r
-    #     default value no element was found.  Note that if the element\r
-    #     has is found, but has no text content, this method returns an\r
-    #     empty string.\r
-    # @defreturn string\r
-\r
-    def findtext(self, path, default=None):\r
-        return ElementPath.findtext(self, path, default)\r
-\r
-    ##\r
-    # Finds all matching subelements, by tag name or path.\r
-    #\r
-    # @param path What element to look for.\r
-    # @return A list or iterator containing all matching elements,\r
-    #    in document order.\r
-    # @defreturn list of Element instances\r
-\r
-    def findall(self, path):\r
-        return ElementPath.findall(self, path)\r
-\r
-    ##\r
-    # Resets an element.  This function removes all subelements, clears\r
-    # all attributes, and sets the text and tail attributes to None.\r
-\r
-    def clear(self):\r
-        self.attrib.clear()\r
-        self._children = []\r
-        self.text = self.tail = None\r
-\r
-    ##\r
-    # Gets an element attribute.\r
-    #\r
-    # @param key What attribute to look for.\r
-    # @param default What to return if the attribute was not found.\r
-    # @return The attribute value, or the default value, if the\r
-    #     attribute was not found.\r
-    # @defreturn string or None\r
-\r
-    def get(self, key, default=None):\r
-        return self.attrib.get(key, default)\r
-\r
-    ##\r
-    # Sets an element attribute.\r
-    #\r
-    # @param key What attribute to set.\r
-    # @param value The attribute value.\r
-\r
-    def set(self, key, value):\r
-        self.attrib[key] = value\r
-\r
-    ##\r
-    # Gets a list of attribute names.  The names are returned in an\r
-    # arbitrary order (just like for an ordinary Python dictionary).\r
-    #\r
-    # @return A list of element attribute names.\r
-    # @defreturn list of strings\r
-\r
-    def keys(self):\r
-        return self.attrib.keys()\r
-\r
-    ##\r
-    # Gets element attributes, as a sequence.  The attributes are\r
-    # returned in an arbitrary order.\r
-    #\r
-    # @return A list of (name, value) tuples for all attributes.\r
-    # @defreturn list of (string, string) tuples\r
-\r
-    def items(self):\r
-        return self.attrib.items()\r
-\r
-    ##\r
-    # Creates a tree iterator.  The iterator loops over this element\r
-    # and all subelements, in document order, and returns all elements\r
-    # with a matching tag.\r
-    # <p>\r
-    # If the tree structure is modified during iteration, the result\r
-    # is undefined.\r
-    #\r
-    # @param tag What tags to look for (default is to return all elements).\r
-    # @return A list or iterator containing all the matching elements.\r
-    # @defreturn list or iterator\r
-\r
-    def getiterator(self, tag=None):\r
-        nodes = []\r
-        if tag == "*":\r
-            tag = None\r
-        if tag is None or self.tag == tag:\r
-            nodes.append(self)\r
-        for node in self._children:\r
-            nodes.extend(node.getiterator(tag))\r
-        return nodes\r
-\r
-# compatibility\r
-_Element = _ElementInterface\r
-\r
-##\r
-# Element factory.  This function returns an object implementing the\r
-# standard Element interface.  The exact class or type of that object\r
-# is implementation dependent, but it will always be compatible with\r
-# the {@link #_ElementInterface} class in this module.\r
-# <p>\r
-# The element name, attribute names, and attribute values can be\r
-# either 8-bit ASCII strings or Unicode strings.\r
-#\r
-# @param tag The element name.\r
-# @param attrib An optional dictionary, containing element attributes.\r
-# @param **extra Additional attributes, given as keyword arguments.\r
-# @return An element instance.\r
-# @defreturn Element\r
-\r
-def Element(tag, attrib={}, **extra):\r
-    attrib = attrib.copy()\r
-    attrib.update(extra)\r
-    return _ElementInterface(tag, attrib)\r
-\r
-##\r
-# Subelement factory.  This function creates an element instance, and\r
-# appends it to an existing element.\r
-# <p>\r
-# The element name, attribute names, and attribute values can be\r
-# either 8-bit ASCII strings or Unicode strings.\r
-#\r
-# @param parent The parent element.\r
-# @param tag The subelement name.\r
-# @param attrib An optional dictionary, containing element attributes.\r
-# @param **extra Additional attributes, given as keyword arguments.\r
-# @return An element instance.\r
-# @defreturn Element\r
-\r
-def SubElement(parent, tag, attrib={}, **extra):\r
-    attrib = attrib.copy()\r
-    attrib.update(extra)\r
-    element = parent.makeelement(tag, attrib)\r
-    parent.append(element)\r
-    return element\r
-\r
-##\r
-# Comment element factory.  This factory function creates a special\r
-# element that will be serialized as an XML comment.\r
-# <p>\r
-# The comment string can be either an 8-bit ASCII string or a Unicode\r
-# string.\r
-#\r
-# @param text A string containing the comment string.\r
-# @return An element instance, representing a comment.\r
-# @defreturn Element\r
-\r
-def Comment(text=None):\r
-    element = Element(Comment)\r
-    element.text = text\r
-    return element\r
-\r
-##\r
-# PI element factory.  This factory function creates a special element\r
-# that will be serialized as an XML processing instruction.\r
-#\r
-# @param target A string containing the PI target.\r
-# @param text A string containing the PI contents, if any.\r
-# @return An element instance, representing a PI.\r
-# @defreturn Element\r
-\r
-def ProcessingInstruction(target, text=None):\r
-    element = Element(ProcessingInstruction)\r
-    element.text = target\r
-    if text:\r
-        element.text = element.text + " " + text\r
-    return element\r
-\r
-PI = ProcessingInstruction\r
-\r
-##\r
-# QName wrapper.  This can be used to wrap a QName attribute value, in\r
-# order to get proper namespace handling on output.\r
-#\r
-# @param text A string containing the QName value, in the form {uri}local,\r
-#     or, if the tag argument is given, the URI part of a QName.\r
-# @param tag Optional tag.  If given, the first argument is interpreted as\r
-#     an URI, and this argument is interpreted as a local name.\r
-# @return An opaque object, representing the QName.\r
-\r
-class QName:\r
-    def __init__(self, text_or_uri, tag=None):\r
-        if tag:\r
-            text_or_uri = "{%s}%s" % (text_or_uri, tag)\r
-        self.text = text_or_uri\r
-    def __str__(self):\r
-        return self.text\r
-    def __hash__(self):\r
-        return hash(self.text)\r
-    def __cmp__(self, other):\r
-        if isinstance(other, QName):\r
-            return cmp(self.text, other.text)\r
-        return cmp(self.text, other)\r
-\r
-##\r
-# ElementTree wrapper class.  This class represents an entire element\r
-# hierarchy, and adds some extra support for serialization to and from\r
-# standard XML.\r
-#\r
-# @param element Optional root element.\r
-# @keyparam file Optional file handle or name.  If given, the\r
-#     tree is initialized with the contents of this XML file.\r
-\r
-class ElementTree:\r
-\r
-    def __init__(self, element=None, file=None):\r
-        assert element is None or iselement(element)\r
-        self._root = element # first node\r
-        if file:\r
-            self.parse(file)\r
-\r
-    ##\r
-    # Gets the root element for this tree.\r
-    #\r
-    # @return An element instance.\r
-    # @defreturn Element\r
-\r
-    def getroot(self):\r
-        return self._root\r
-\r
-    ##\r
-    # Replaces the root element for this tree.  This discards the\r
-    # current contents of the tree, and replaces it with the given\r
-    # element.  Use with care.\r
-    #\r
-    # @param element An element instance.\r
-\r
-    def _setroot(self, element):\r
-        assert iselement(element)\r
-        self._root = element\r
-\r
-    ##\r
-    # Loads an external XML document into this element tree.\r
-    #\r
-    # @param source A file name or file object.\r
-    # @param parser An optional parser instance.  If not given, the\r
-    #     standard {@link XMLTreeBuilder} parser is used.\r
-    # @return The document root element.\r
-    # @defreturn Element\r
-\r
-    def parse(self, source, parser=None):\r
-        if not hasattr(source, "read"):\r
-            source = open(source, "rb")\r
-        if not parser:\r
-            parser = XMLTreeBuilder()\r
-        while 1:\r
-            data = source.read(32768)\r
-            if not data:\r
-                break\r
-            parser.feed(data)\r
-        self._root = parser.close()\r
-        return self._root\r
-\r
-    ##\r
-    # Creates a tree iterator for the root element.  The iterator loops\r
-    # over all elements in this tree, in document order.\r
-    #\r
-    # @param tag What tags to look for (default is to return all elements)\r
-    # @return An iterator.\r
-    # @defreturn iterator\r
-\r
-    def getiterator(self, tag=None):\r
-        assert self._root is not None\r
-        return self._root.getiterator(tag)\r
-\r
-    ##\r
-    # Finds the first toplevel element with given tag.\r
-    # Same as getroot().find(path).\r
-    #\r
-    # @param path What element to look for.\r
-    # @return The first matching element, or None if no element was found.\r
-    # @defreturn Element or None\r
-\r
-    def find(self, path):\r
-        assert self._root is not None\r
-        if path[:1] == "/":\r
-            path = "." + path\r
-        return self._root.find(path)\r
-\r
-    ##\r
-    # Finds the element text for the first toplevel element with given\r
-    # tag.  Same as getroot().findtext(path).\r
-    #\r
-    # @param path What toplevel element to look for.\r
-    # @param default What to return if the element was not found.\r
-    # @return The text content of the first matching element, or the\r
-    #     default value no element was found.  Note that if the element\r
-    #     has is found, but has no text content, this method returns an\r
-    #     empty string.\r
-    # @defreturn string\r
-\r
-    def findtext(self, path, default=None):\r
-        assert self._root is not None\r
-        if path[:1] == "/":\r
-            path = "." + path\r
-        return self._root.findtext(path, default)\r
-\r
-    ##\r
-    # Finds all toplevel elements with the given tag.\r
-    # Same as getroot().findall(path).\r
-    #\r
-    # @param path What element to look for.\r
-    # @return A list or iterator containing all matching elements,\r
-    #    in document order.\r
-    # @defreturn list of Element instances\r
-\r
-    def findall(self, path):\r
-        assert self._root is not None\r
-        if path[:1] == "/":\r
-            path = "." + path\r
-        return self._root.findall(path)\r
-\r
-    ##\r
-    # Writes the element tree to a file, as XML.\r
-    #\r
-    # @param file A file name, or a file object opened for writing.\r
-    # @param encoding Optional output encoding (default is US-ASCII).\r
-\r
-    def write(self, file, encoding="us-ascii"):\r
-        assert self._root is not None\r
-        if not hasattr(file, "write"):\r
-            file = open(file, "wb")\r
-        if not encoding:\r
-            encoding = "us-ascii"\r
-        elif encoding != "utf-8" and encoding != "us-ascii":\r
-            file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)\r
-        self._write(file, self._root, encoding, {})\r
-\r
-    def _write(self, file, node, encoding, namespaces):\r
-        # write XML to file\r
-        tag = node.tag\r
-        if tag is Comment:\r
-            file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))\r
-        elif tag is ProcessingInstruction:\r
-            file.write("<?%s?>" % _escape_cdata(node.text, encoding))\r
-        else:\r
-            items = node.items()\r
-            xmlns_items = [] # new namespaces in this scope\r
-            try:\r
-                if isinstance(tag, QName) or tag[:1] == "{":\r
-                    tag, xmlns = fixtag(tag, namespaces)\r
-                    if xmlns: xmlns_items.append(xmlns)\r
-            except TypeError:\r
-                _raise_serialization_error(tag)\r
-            file.write("<" + _encode(tag, encoding))\r
-            if items or xmlns_items:\r
-                items.sort() # lexical order\r
-                for k, v in items:\r
-                    try:\r
-                        if isinstance(k, QName) or k[:1] == "{":\r
-                            k, xmlns = fixtag(k, namespaces)\r
-                            if xmlns: xmlns_items.append(xmlns)\r
-                    except TypeError:\r
-                        _raise_serialization_error(k)\r
-                    try:\r
-                        if isinstance(v, QName):\r
-                            v, xmlns = fixtag(v, namespaces)\r
-                            if xmlns: xmlns_items.append(xmlns)\r
-                    except TypeError:\r
-                        _raise_serialization_error(v)\r
-                    file.write(" %s=\"%s\"" % (_encode(k, encoding),\r
-                                               _escape_attrib(v, encoding)))\r
-                for k, v in xmlns_items:\r
-                    file.write(" %s=\"%s\"" % (_encode(k, encoding),\r
-                                               _escape_attrib(v, encoding)))\r
-            if node.text or len(node):\r
-                file.write(">")\r
-                if node.text:\r
-                    file.write(_escape_cdata(node.text, encoding))\r
-                for n in node:\r
-                    self._write(file, n, encoding, namespaces)\r
-                file.write("</" + _encode(tag, encoding) + ">")\r
-            else:\r
-                file.write(" />")\r
-            for k, v in xmlns_items:\r
-                del namespaces[v]\r
-        if node.tail:\r
-            file.write(_escape_cdata(node.tail, encoding))\r
-\r
-# --------------------------------------------------------------------\r
-# helpers\r
-\r
-##\r
-# Checks if an object appears to be a valid element object.\r
-#\r
-# @param An element instance.\r
-# @return A true value if this is an element object.\r
-# @defreturn flag\r
-\r
-def iselement(element):\r
-    # FIXME: not sure about this; might be a better idea to look\r
-    # for tag/attrib/text attributes\r
-    return isinstance(element, _ElementInterface) or hasattr(element, "tag")\r
-\r
-##\r
-# Writes an element tree or element structure to sys.stdout.  This\r
-# function should be used for debugging only.\r
-# <p>\r
-# The exact output format is implementation dependent.  In this\r
-# version, it's written as an ordinary XML file.\r
-#\r
-# @param elem An element tree or an individual element.\r
-\r
-def dump(elem):\r
-    # debugging\r
-    if not isinstance(elem, ElementTree):\r
-        elem = ElementTree(elem)\r
-    elem.write(sys.stdout)\r
-    tail = elem.getroot().tail\r
-    if not tail or tail[-1] != "\n":\r
-        sys.stdout.write("\n")\r
-\r
-def _encode(s, encoding):\r
-    try:\r
-        return s.encode(encoding)\r
-    except AttributeError:\r
-        return s # 1.5.2: assume the string uses the right encoding\r
-\r
-if sys.version[:3] == "1.5":\r
-    _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2\r
-else:\r
-    _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))\r
-\r
-_escape_map = {\r
-    "&": "&amp;",\r
-    "<": "&lt;",\r
-    ">": "&gt;",\r
-    '"': "&quot;",\r
-}\r
-\r
-_namespace_map = {\r
-    # "well-known" namespace prefixes\r
-    "http://www.w3.org/XML/1998/namespace": "xml",\r
-    "http://www.w3.org/1999/xhtml": "html",\r
-    "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",\r
-    "http://schemas.xmlsoap.org/wsdl/": "wsdl",\r
-}\r
-\r
-def _raise_serialization_error(text):\r
-    raise TypeError(\r
-        "cannot serialize %r (type %s)" % (text, type(text).__name__)\r
-        )\r
-\r
-def _encode_entity(text, pattern=_escape):\r
-    # map reserved and non-ascii characters to numerical entities\r
-    def escape_entities(m, map=_escape_map):\r
-        out = []\r
-        append = out.append\r
-        for char in m.group():\r
-            text = map.get(char)\r
-            if text is None:\r
-                text = "&#%d;" % ord(char)\r
-            append(text)\r
-        return string.join(out, "")\r
-    try:\r
-        return _encode(pattern.sub(escape_entities, text), "ascii")\r
-    except TypeError:\r
-        _raise_serialization_error(text)\r
-\r
-#\r
-# the following functions assume an ascii-compatible encoding\r
-# (or "utf-16")\r
-\r
-def _escape_cdata(text, encoding=None, replace=string.replace):\r
-    # escape character data\r
-    try:\r
-        if encoding:\r
-            try:\r
-                text = _encode(text, encoding)\r
-            except UnicodeError:\r
-                return _encode_entity(text)\r
-        text = replace(text, "&", "&amp;")\r
-        text = replace(text, "<", "&lt;")\r
-        text = replace(text, ">", "&gt;")\r
-        return text\r
-    except (TypeError, AttributeError):\r
-        _raise_serialization_error(text)\r
-\r
-def _escape_attrib(text, encoding=None, replace=string.replace):\r
-    # escape attribute value\r
-    try:\r
-        if encoding:\r
-            try:\r
-                text = _encode(text, encoding)\r
-            except UnicodeError:\r
-                return _encode_entity(text)\r
-        text = replace(text, "&", "&amp;")\r
-        text = replace(text, "'", "&apos;") # FIXME: overkill\r
-        text = replace(text, "\"", "&quot;")\r
-        text = replace(text, "<", "&lt;")\r
-        text = replace(text, ">", "&gt;")\r
-        return text\r
-    except (TypeError, AttributeError):\r
-        _raise_serialization_error(text)\r
-\r
-def fixtag(tag, namespaces):\r
-    # given a decorated tag (of the form {uri}tag), return prefixed\r
-    # tag and namespace declaration, if any\r
-    if isinstance(tag, QName):\r
-        tag = tag.text\r
-    namespace_uri, tag = string.split(tag[1:], "}", 1)\r
-    prefix = namespaces.get(namespace_uri)\r
-    if prefix is None:\r
-        prefix = _namespace_map.get(namespace_uri)\r
-        if prefix is None:\r
-            prefix = "ns%d" % len(namespaces)\r
-        namespaces[namespace_uri] = prefix\r
-        if prefix == "xml":\r
-            xmlns = None\r
-        else:\r
-            xmlns = ("xmlns:%s" % prefix, namespace_uri)\r
-    else:\r
-        xmlns = None\r
-    return "%s:%s" % (prefix, tag), xmlns\r
-\r
-##\r
-# Parses an XML document into an element tree.\r
-#\r
-# @param source A filename or file object containing XML data.\r
-# @param parser An optional parser instance.  If not given, the\r
-#     standard {@link XMLTreeBuilder} parser is used.\r
-# @return An ElementTree instance\r
-\r
-def parse(source, parser=None):\r
-    tree = ElementTree()\r
-    tree.parse(source, parser)\r
-    return tree\r
-\r
-##\r
-# Parses an XML document into an element tree incrementally, and reports\r
-# what's going on to the user.\r
-#\r
-# @param source A filename or file object containing XML data.\r
-# @param events A list of events to report back.  If omitted, only "end"\r
-#     events are reported.\r
-# @return A (event, elem) iterator.\r
-\r
-class iterparse:\r
-\r
-    def __init__(self, source, events=None):\r
-        if not hasattr(source, "read"):\r
-            source = open(source, "rb")\r
-        self._file = source\r
-        self._events = []\r
-        self._index = 0\r
-        self.root = self._root = None\r
-        self._parser = XMLTreeBuilder()\r
-        # wire up the parser for event reporting\r
-        parser = self._parser._parser\r
-        append = self._events.append\r
-        if events is None:\r
-            events = ["end"]\r
-        for event in events:\r
-            if event == "start":\r
-                try:\r
-                    parser.ordered_attributes = 1\r
-                    parser.specified_attributes = 1\r
-                    def handler(tag, attrib_in, event=event, append=append,\r
-                                start=self._parser._start_list):\r
-                        append((event, start(tag, attrib_in)))\r
-                    parser.StartElementHandler = handler\r
-                except AttributeError:\r
-                    def handler(tag, attrib_in, event=event, append=append,\r
-                                start=self._parser._start):\r
-                        append((event, start(tag, attrib_in)))\r
-                    parser.StartElementHandler = handler\r
-            elif event == "end":\r
-                def handler(tag, event=event, append=append,\r
-                            end=self._parser._end):\r
-                    append((event, end(tag)))\r
-                parser.EndElementHandler = handler\r
-            elif event == "start-ns":\r
-                def handler(prefix, uri, event=event, append=append):\r
-                    try:\r
-                        uri = _encode(uri, "ascii")\r
-                    except UnicodeError:\r
-                        pass\r
-                    append((event, (prefix or "", uri)))\r
-                parser.StartNamespaceDeclHandler = handler\r
-            elif event == "end-ns":\r
-                def handler(prefix, event=event, append=append):\r
-                    append((event, None))\r
-                parser.EndNamespaceDeclHandler = handler\r
-\r
-    def next(self):\r
-        while 1:\r
-            try:\r
-                item = self._events[self._index]\r
-            except IndexError:\r
-                if self._parser is None:\r
-                    self.root = self._root\r
-                    try:\r
-                        raise StopIteration\r
-                    except NameError:\r
-                        raise IndexError\r
-                # load event buffer\r
-                del self._events[:]\r
-                self._index = 0\r
-                data = self._file.read(16384)\r
-                if data:\r
-                    self._parser.feed(data)\r
-                else:\r
-                    self._root = self._parser.close()\r
-                    self._parser = None\r
-            else:\r
-                self._index = self._index + 1\r
-                return item\r
-\r
-    try:\r
-        iter\r
-        def __iter__(self):\r
-            return self\r
-    except NameError:\r
-        def __getitem__(self, index):\r
-            return self.next()\r
-\r
-##\r
-# Parses an XML document from a string constant.  This function can\r
-# be used to embed "XML literals" in Python code.\r
-#\r
-# @param source A string containing XML data.\r
-# @return An Element instance.\r
-# @defreturn Element\r
-\r
-def XML(text):\r
-    parser = XMLTreeBuilder()\r
-    parser.feed(text)\r
-    return parser.close()\r
-\r
-##\r
-# Parses an XML document from a string constant, and also returns\r
-# a dictionary which maps from element id:s to elements.\r
-#\r
-# @param source A string containing XML data.\r
-# @return A tuple containing an Element instance and a dictionary.\r
-# @defreturn (Element, dictionary)\r
-\r
-def XMLID(text):\r
-    parser = XMLTreeBuilder()\r
-    parser.feed(text)\r
-    tree = parser.close()\r
-    ids = {}\r
-    for elem in tree.getiterator():\r
-        id = elem.get("id")\r
-        if id:\r
-            ids[id] = elem\r
-    return tree, ids\r
-\r
-##\r
-# Parses an XML document from a string constant.  Same as {@link #XML}.\r
-#\r
-# @def fromstring(text)\r
-# @param source A string containing XML data.\r
-# @return An Element instance.\r
-# @defreturn Element\r
-\r
-fromstring = XML\r
-\r
-##\r
-# Generates a string representation of an XML element, including all\r
-# subelements.\r
-#\r
-# @param element An Element instance.\r
-# @return An encoded string containing the XML data.\r
-# @defreturn string\r
-\r
-def tostring(element, encoding=None):\r
-    class dummy:\r
-        pass\r
-    data = []\r
-    file = dummy()\r
-    file.write = data.append\r
-    ElementTree(element).write(file, encoding)\r
-    return string.join(data, "")\r
-\r
-##\r
-# Generic element structure builder.  This builder converts a sequence\r
-# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link\r
-# #TreeBuilder.end} method calls to a well-formed element structure.\r
-# <p>\r
-# You can use this class to build an element structure using a custom XML\r
-# parser, or a parser for some other XML-like format.\r
-#\r
-# @param element_factory Optional element factory.  This factory\r
-#    is called to create new Element instances, as necessary.\r
-\r
-class TreeBuilder:\r
-\r
-    def __init__(self, element_factory=None):\r
-        self._data = [] # data collector\r
-        self._elem = [] # element stack\r
-        self._last = None # last element\r
-        self._tail = None # true if we're after an end tag\r
-        if element_factory is None:\r
-            element_factory = _ElementInterface\r
-        self._factory = element_factory\r
-\r
-    ##\r
-    # Flushes the parser buffers, and returns the toplevel documen\r
-    # element.\r
-    #\r
-    # @return An Element instance.\r
-    # @defreturn Element\r
-\r
-    def close(self):\r
-        assert len(self._elem) == 0, "missing end tags"\r
-        assert self._last != None, "missing toplevel element"\r
-        return self._last\r
-\r
-    def _flush(self):\r
-        if self._data:\r
-            if self._last is not None:\r
-                text = string.join(self._data, "")\r
-                if self._tail:\r
-                    assert self._last.tail is None, "internal error (tail)"\r
-                    self._last.tail = text\r
-                else:\r
-                    assert self._last.text is None, "internal error (text)"\r
-                    self._last.text = text\r
-            self._data = []\r
-\r
-    ##\r
-    # Adds text to the current element.\r
-    #\r
-    # @param data A string.  This should be either an 8-bit string\r
-    #    containing ASCII text, or a Unicode string.\r
-\r
-    def data(self, data):\r
-        self._data.append(data)\r
-\r
-    ##\r
-    # Opens a new element.\r
-    #\r
-    # @param tag The element name.\r
-    # @param attrib A dictionary containing element attributes.\r
-    # @return The opened element.\r
-    # @defreturn Element\r
-\r
-    def start(self, tag, attrs):\r
-        self._flush()\r
-        self._last = elem = self._factory(tag, attrs)\r
-        if self._elem:\r
-            self._elem[-1].append(elem)\r
-        self._elem.append(elem)\r
-        self._tail = 0\r
-        return elem\r
-\r
-    ##\r
-    # Closes the current element.\r
-    #\r
-    # @param tag The element name.\r
-    # @return The closed element.\r
-    # @defreturn Element\r
-\r
-    def end(self, tag):\r
-        self._flush()\r
-        self._last = self._elem.pop()\r
-        assert self._last.tag == tag,\\r
-               "end tag mismatch (expected %s, got %s)" % (\r
-                   self._last.tag, tag)\r
-        self._tail = 1\r
-        return self._last\r
-\r
-##\r
-# Element structure builder for XML source data, based on the\r
-# <b>expat</b> parser.\r
-#\r
-# @keyparam target Target object.  If omitted, the builder uses an\r
-#     instance of the standard {@link #TreeBuilder} class.\r
-# @keyparam html Predefine HTML entities.  This flag is not supported\r
-#     by the current implementation.\r
-# @see #ElementTree\r
-# @see #TreeBuilder\r
-\r
-class XMLTreeBuilder:\r
-\r
-    def __init__(self, html=0, target=None):\r
-        try:\r
-            from xmlcore.parsers import expat\r
-        except ImportError:\r
-            raise ImportError(\r
-                "No module named expat; use SimpleXMLTreeBuilder instead"\r
-                )\r
-        self._parser = parser = expat.ParserCreate(None, "}")\r
-        if target is None:\r
-            target = TreeBuilder()\r
-        self._target = target\r
-        self._names = {} # name memo cache\r
-        # callbacks\r
-        parser.DefaultHandlerExpand = self._default\r
-        parser.StartElementHandler = self._start\r
-        parser.EndElementHandler = self._end\r
-        parser.CharacterDataHandler = self._data\r
-        # let expat do the buffering, if supported\r
-        try:\r
-            self._parser.buffer_text = 1\r
-        except AttributeError:\r
-            pass\r
-        # use new-style attribute handling, if supported\r
-        try:\r
-            self._parser.ordered_attributes = 1\r
-            self._parser.specified_attributes = 1\r
-            parser.StartElementHandler = self._start_list\r
-        except AttributeError:\r
-            pass\r
-        encoding = None\r
-        if not parser.returns_unicode:\r
-            encoding = "utf-8"\r
-        # target.xml(encoding, None)\r
-        self._doctype = None\r
-        self.entity = {}\r
-\r
-    def _fixtext(self, text):\r
-        # convert text string to ascii, if possible\r
-        try:\r
-            return _encode(text, "ascii")\r
-        except UnicodeError:\r
-            return text\r
-\r
-    def _fixname(self, key):\r
-        # expand qname, and convert name string to ascii, if possible\r
-        try:\r
-            name = self._names[key]\r
-        except KeyError:\r
-            name = key\r
-            if "}" in name:\r
-                name = "{" + name\r
-            self._names[key] = name = self._fixtext(name)\r
-        return name\r
-\r
-    def _start(self, tag, attrib_in):\r
-        fixname = self._fixname\r
-        tag = fixname(tag)\r
-        attrib = {}\r
-        for key, value in attrib_in.items():\r
-            attrib[fixname(key)] = self._fixtext(value)\r
-        return self._target.start(tag, attrib)\r
-\r
-    def _start_list(self, tag, attrib_in):\r
-        fixname = self._fixname\r
-        tag = fixname(tag)\r
-        attrib = {}\r
-        if attrib_in:\r
-            for i in range(0, len(attrib_in), 2):\r
-                attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])\r
-        return self._target.start(tag, attrib)\r
-\r
-    def _data(self, text):\r
-        return self._target.data(self._fixtext(text))\r
-\r
-    def _end(self, tag):\r
-        return self._target.end(self._fixname(tag))\r
-\r
-    def _default(self, text):\r
-        prefix = text[:1]\r
-        if prefix == "&":\r
-            # deal with undefined entities\r
-            try:\r
-                self._target.data(self.entity[text[1:-1]])\r
-            except KeyError:\r
-                from xmlcore.parsers import expat\r
-                raise expat.error(\r
-                    "undefined entity %s: line %d, column %d" %\r
-                    (text, self._parser.ErrorLineNumber,\r
-                    self._parser.ErrorColumnNumber)\r
-                    )\r
-        elif prefix == "<" and text[:9] == "<!DOCTYPE":\r
-            self._doctype = [] # inside a doctype declaration\r
-        elif self._doctype is not None:\r
-            # parse doctype contents\r
-            if prefix == ">":\r
-                self._doctype = None\r
-                return\r
-            text = string.strip(text)\r
-            if not text:\r
-                return\r
-            self._doctype.append(text)\r
-            n = len(self._doctype)\r
-            if n > 2:\r
-                type = self._doctype[1]\r
-                if type == "PUBLIC" and n == 4:\r
-                    name, type, pubid, system = self._doctype\r
-                elif type == "SYSTEM" and n == 3:\r
-                    name, type, system = self._doctype\r
-                    pubid = None\r
-                else:\r
-                    return\r
-                if pubid:\r
-                    pubid = pubid[1:-1]\r
-                self.doctype(name, pubid, system[1:-1])\r
-                self._doctype = None\r
-\r
-    ##\r
-    # Handles a doctype declaration.\r
-    #\r
-    # @param name Doctype name.\r
-    # @param pubid Public identifier.\r
-    # @param system System identifier.\r
-\r
-    def doctype(self, name, pubid, system):\r
-        pass\r
-\r
-    ##\r
-    # Feeds data to the parser.\r
-    #\r
-    # @param data Encoded data.\r
-\r
-    def feed(self, data):\r
-        self._parser.Parse(data, 0)\r
-\r
-    ##\r
-    # Finishes feeding data to the parser.\r
-    #\r
-    # @return An element structure.\r
-    # @defreturn Element\r
-\r
-    def close(self):\r
-        self._parser.Parse("", 1) # end of data\r
-        tree = self._target.close()\r
-        del self._target, self._parser # get rid of circular references\r
-        return tree\r
+#
+# ElementTree
+# $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $
+#
+# light-weight XML support for Python 1.5.2 and later.
+#
+# history:
+# 2001-10-20 fl   created (from various sources)
+# 2001-11-01 fl   return root from parse method
+# 2002-02-16 fl   sort attributes in lexical order
+# 2002-04-06 fl   TreeBuilder refactoring, added PythonDoc markup
+# 2002-05-01 fl   finished TreeBuilder refactoring
+# 2002-07-14 fl   added basic namespace support to ElementTree.write
+# 2002-07-25 fl   added QName attribute support
+# 2002-10-20 fl   fixed encoding in write
+# 2002-11-24 fl   changed default encoding to ascii; fixed attribute encoding
+# 2002-11-27 fl   accept file objects or file names for parse/write
+# 2002-12-04 fl   moved XMLTreeBuilder back to this module
+# 2003-01-11 fl   fixed entity encoding glitch for us-ascii
+# 2003-02-13 fl   added XML literal factory
+# 2003-02-21 fl   added ProcessingInstruction/PI factory
+# 2003-05-11 fl   added tostring/fromstring helpers
+# 2003-05-26 fl   added ElementPath support
+# 2003-07-05 fl   added makeelement factory method
+# 2003-07-28 fl   added more well-known namespace prefixes
+# 2003-08-15 fl   fixed typo in ElementTree.findtext (Thomas Dartsch)
+# 2003-09-04 fl   fall back on emulator if ElementPath is not installed
+# 2003-10-31 fl   markup updates
+# 2003-11-15 fl   fixed nested namespace bug
+# 2004-03-28 fl   added XMLID helper
+# 2004-06-02 fl   added default support to findtext
+# 2004-06-08 fl   fixed encoding of non-ascii element/attribute names
+# 2004-08-23 fl   take advantage of post-2.1 expat features
+# 2005-02-01 fl   added iterparse implementation
+# 2005-03-02 fl   fixed iterparse support for pre-2.2 versions
+#
+# Copyright (c) 1999-2005 by Fredrik Lundh.  All rights reserved.
+#
+# fredrik@pythonware.com
+# http://www.pythonware.com
+#
+# --------------------------------------------------------------------
+# The ElementTree toolkit is
+#
+# Copyright (c) 1999-2005 by Fredrik Lundh
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------
+
+__all__ = [
+    # public symbols
+    "Comment",
+    "dump",
+    "Element", "ElementTree",
+    "fromstring",
+    "iselement", "iterparse",
+    "parse",
+    "PI", "ProcessingInstruction",
+    "QName",
+    "SubElement",
+    "tostring",
+    "TreeBuilder",
+    "VERSION", "XML",
+    "XMLTreeBuilder",
+    ]
+
+##
+# The <b>Element</b> type is a flexible container object, designed to
+# store hierarchical data structures in memory. The type can be
+# described as a cross between a list and a dictionary.
+# <p>
+# Each element has a number of properties associated with it:
+# <ul>
+# <li>a <i>tag</i>. This is a string identifying what kind of data
+# this element represents (the element type, in other words).</li>
+# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
+# <li>a <i>text</i> string.</li>
+# <li>an optional <i>tail</i> string.</li>
+# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
+# </ul>
+#
+# To create an element instance, use the {@link #Element} or {@link
+# #SubElement} factory functions.
+# <p>
+# The {@link #ElementTree} class can be used to wrap an element
+# structure, and convert it from and to XML.
+##
+
+import string, sys, re
+
+class _SimpleElementPath:
+    # emulate pre-1.2 find/findtext/findall behaviour
+    def find(self, element, tag):
+        for elem in element:
+            if elem.tag == tag:
+                return elem
+        return None
+    def findtext(self, element, tag, default=None):
+        for elem in element:
+            if elem.tag == tag:
+                return elem.text or ""
+        return default
+    def findall(self, element, tag):
+        if tag[:3] == ".//":
+            return element.getiterator(tag[3:])
+        result = []
+        for elem in element:
+            if elem.tag == tag:
+                result.append(elem)
+        return result
+
+try:
+    import ElementPath
+except ImportError:
+    # FIXME: issue warning in this case?
+    ElementPath = _SimpleElementPath()
+
+# TODO: add support for custom namespace resolvers/default namespaces
+# TODO: add improved support for incremental parsing
+
+VERSION = "1.2.6"
+
+##
+# Internal element class.  This class defines the Element interface,
+# and provides a reference implementation of this interface.
+# <p>
+# You should not create instances of this class directly.  Use the
+# appropriate factory functions instead, such as {@link #Element}
+# and {@link #SubElement}.
+#
+# @see Element
+# @see SubElement
+# @see Comment
+# @see ProcessingInstruction
+
+class _ElementInterface:
+    # <tag attrib>text<child/>...</tag>tail
+
+    ##
+    # (Attribute) Element tag.
+
+    tag = None
+
+    ##
+    # (Attribute) Element attribute dictionary.  Where possible, use
+    # {@link #_ElementInterface.get},
+    # {@link #_ElementInterface.set},
+    # {@link #_ElementInterface.keys}, and
+    # {@link #_ElementInterface.items} to access
+    # element attributes.
+
+    attrib = None
+
+    ##
+    # (Attribute) Text before first subelement.  This is either a
+    # string or the value None, if there was no text.
+
+    text = None
+
+    ##
+    # (Attribute) Text after this element's end tag, but before the
+    # next sibling element's start tag.  This is either a string or
+    # the value None, if there was no text.
+
+    tail = None # text after end tag, if any
+
+    def __init__(self, tag, attrib):
+        self.tag = tag
+        self.attrib = attrib
+        self._children = []
+
+    def __repr__(self):
+        return "<Element %s at %x>" % (self.tag, id(self))
+
+    ##
+    # Creates a new element object of the same type as this element.
+    #
+    # @param tag Element tag.
+    # @param attrib Element attributes, given as a dictionary.
+    # @return A new element instance.
+
+    def makeelement(self, tag, attrib):
+        return Element(tag, attrib)
+
+    ##
+    # Returns the number of subelements.
+    #
+    # @return The number of subelements.
+
+    def __len__(self):
+        return len(self._children)
+
+    ##
+    # Returns the given subelement.
+    #
+    # @param index What subelement to return.
+    # @return The given subelement.
+    # @exception IndexError If the given element does not exist.
+
+    def __getitem__(self, index):
+        return self._children[index]
+
+    ##
+    # Replaces the given subelement.
+    #
+    # @param index What subelement to replace.
+    # @param element The new element value.
+    # @exception IndexError If the given element does not exist.
+    # @exception AssertionError If element is not a valid object.
+
+    def __setitem__(self, index, element):
+        assert iselement(element)
+        self._children[index] = element
+
+    ##
+    # Deletes the given subelement.
+    #
+    # @param index What subelement to delete.
+    # @exception IndexError If the given element does not exist.
+
+    def __delitem__(self, index):
+        del self._children[index]
+
+    ##
+    # Returns a list containing subelements in the given range.
+    #
+    # @param start The first subelement to return.
+    # @param stop The first subelement that shouldn't be returned.
+    # @return A sequence object containing subelements.
+
+    def __getslice__(self, start, stop):
+        return self._children[start:stop]
+
+    ##
+    # Replaces a number of subelements with elements from a sequence.
+    #
+    # @param start The first subelement to replace.
+    # @param stop The first subelement that shouldn't be replaced.
+    # @param elements A sequence object with zero or more elements.
+    # @exception AssertionError If a sequence member is not a valid object.
+
+    def __setslice__(self, start, stop, elements):
+        for element in elements:
+            assert iselement(element)
+        self._children[start:stop] = list(elements)
+
+    ##
+    # Deletes a number of subelements.
+    #
+    # @param start The first subelement to delete.
+    # @param stop The first subelement to leave in there.
+
+    def __delslice__(self, start, stop):
+        del self._children[start:stop]
+
+    ##
+    # Adds a subelement to the end of this element.
+    #
+    # @param element The element to add.
+    # @exception AssertionError If a sequence member is not a valid object.
+
+    def append(self, element):
+        assert iselement(element)
+        self._children.append(element)
+
+    ##
+    # Inserts a subelement at the given position in this element.
+    #
+    # @param index Where to insert the new subelement.
+    # @exception AssertionError If the element is not a valid object.
+
+    def insert(self, index, element):
+        assert iselement(element)
+        self._children.insert(index, element)
+
+    ##
+    # Removes a matching subelement.  Unlike the <b>find</b> methods,
+    # this method compares elements based on identity, not on tag
+    # value or contents.
+    #
+    # @param element What element to remove.
+    # @exception ValueError If a matching element could not be found.
+    # @exception AssertionError If the element is not a valid object.
+
+    def remove(self, element):
+        assert iselement(element)
+        self._children.remove(element)
+
+    ##
+    # Returns all subelements.  The elements are returned in document
+    # order.
+    #
+    # @return A list of subelements.
+    # @defreturn list of Element instances
+
+    def getchildren(self):
+        return self._children
+
+    ##
+    # Finds the first matching subelement, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @return The first matching element, or None if no element was found.
+    # @defreturn Element or None
+
+    def find(self, path):
+        return ElementPath.find(self, path)
+
+    ##
+    # Finds text for the first matching subelement, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @param default What to return if the element was not found.
+    # @return The text content of the first matching element, or the
+    #     default value no element was found.  Note that if the element
+    #     has is found, but has no text content, this method returns an
+    #     empty string.
+    # @defreturn string
+
+    def findtext(self, path, default=None):
+        return ElementPath.findtext(self, path, default)
+
+    ##
+    # Finds all matching subelements, by tag name or path.
+    #
+    # @param path What element to look for.
+    # @return A list or iterator containing all matching elements,
+    #    in document order.
+    # @defreturn list of Element instances
+
+    def findall(self, path):
+        return ElementPath.findall(self, path)
+
+    ##
+    # Resets an element.  This function removes all subelements, clears
+    # all attributes, and sets the text and tail attributes to None.
+
+    def clear(self):
+        self.attrib.clear()
+        self._children = []
+        self.text = self.tail = None
+
+    ##
+    # Gets an element attribute.
+    #
+    # @param key What attribute to look for.
+    # @param default What to return if the attribute was not found.
+    # @return The attribute value, or the default value, if the
+    #     attribute was not found.
+    # @defreturn string or None
+
+    def get(self, key, default=None):
+        return self.attrib.get(key, default)
+
+    ##
+    # Sets an element attribute.
+    #
+    # @param key What attribute to set.
+    # @param value The attribute value.
+
+    def set(self, key, value):
+        self.attrib[key] = value
+
+    ##
+    # Gets a list of attribute names.  The names are returned in an
+    # arbitrary order (just like for an ordinary Python dictionary).
+    #
+    # @return A list of element attribute names.
+    # @defreturn list of strings
+
+    def keys(self):
+        return self.attrib.keys()
+
+    ##
+    # Gets element attributes, as a sequence.  The attributes are
+    # returned in an arbitrary order.
+    #
+    # @return A list of (name, value) tuples for all attributes.
+    # @defreturn list of (string, string) tuples
+
+    def items(self):
+        return self.attrib.items()
+
+    ##
+    # Creates a tree iterator.  The iterator loops over this element
+    # and all subelements, in document order, and returns all elements
+    # with a matching tag.
+    # <p>
+    # If the tree structure is modified during iteration, the result
+    # is undefined.
+    #
+    # @param tag What tags to look for (default is to return all elements).
+    # @return A list or iterator containing all the matching elements.
+    # @defreturn list or iterator
+
+    def getiterator(self, tag=None):
+        nodes = []
+        if tag == "*":
+            tag = None
+        if tag is None or self.tag == tag:
+            nodes.append(self)
+        for node in self._children:
+            nodes.extend(node.getiterator(tag))
+        return nodes
+
+# compatibility
+_Element = _ElementInterface
+
+##
+# Element factory.  This function returns an object implementing the
+# standard Element interface.  The exact class or type of that object
+# is implementation dependent, but it will always be compatible with
+# the {@link #_ElementInterface} class in this module.
+# <p>
+# The element name, attribute names, and attribute values can be
+# either 8-bit ASCII strings or Unicode strings.
+#
+# @param tag The element name.
+# @param attrib An optional dictionary, containing element attributes.
+# @param **extra Additional attributes, given as keyword arguments.
+# @return An element instance.
+# @defreturn Element
+
+def Element(tag, attrib={}, **extra):
+    attrib = attrib.copy()
+    attrib.update(extra)
+    return _ElementInterface(tag, attrib)
+
+##
+# Subelement factory.  This function creates an element instance, and
+# appends it to an existing element.
+# <p>
+# The element name, attribute names, and attribute values can be
+# either 8-bit ASCII strings or Unicode strings.
+#
+# @param parent The parent element.
+# @param tag The subelement name.
+# @param attrib An optional dictionary, containing element attributes.
+# @param **extra Additional attributes, given as keyword arguments.
+# @return An element instance.
+# @defreturn Element
+
+def SubElement(parent, tag, attrib={}, **extra):
+    attrib = attrib.copy()
+    attrib.update(extra)
+    element = parent.makeelement(tag, attrib)
+    parent.append(element)
+    return element
+
+##
+# Comment element factory.  This factory function creates a special
+# element that will be serialized as an XML comment.
+# <p>
+# The comment string can be either an 8-bit ASCII string or a Unicode
+# string.
+#
+# @param text A string containing the comment string.
+# @return An element instance, representing a comment.
+# @defreturn Element
+
+def Comment(text=None):
+    element = Element(Comment)
+    element.text = text
+    return element
+
+##
+# PI element factory.  This factory function creates a special element
+# that will be serialized as an XML processing instruction.
+#
+# @param target A string containing the PI target.
+# @param text A string containing the PI contents, if any.
+# @return An element instance, representing a PI.
+# @defreturn Element
+
+def ProcessingInstruction(target, text=None):
+    element = Element(ProcessingInstruction)
+    element.text = target
+    if text:
+        element.text = element.text + " " + text
+    return element
+
+PI = ProcessingInstruction
+
+##
+# QName wrapper.  This can be used to wrap a QName attribute value, in
+# order to get proper namespace handling on output.
+#
+# @param text A string containing the QName value, in the form {uri}local,
+#     or, if the tag argument is given, the URI part of a QName.
+# @param tag Optional tag.  If given, the first argument is interpreted as
+#     an URI, and this argument is interpreted as a local name.
+# @return An opaque object, representing the QName.
+
+class QName:
+    def __init__(self, text_or_uri, tag=None):
+        if tag:
+            text_or_uri = "{%s}%s" % (text_or_uri, tag)
+        self.text = text_or_uri
+    def __str__(self):
+        return self.text
+    def __hash__(self):
+        return hash(self.text)
+    def __cmp__(self, other):
+        if isinstance(other, QName):
+            return cmp(self.text, other.text)
+        return cmp(self.text, other)
+
+##
+# ElementTree wrapper class.  This class represents an entire element
+# hierarchy, and adds some extra support for serialization to and from
+# standard XML.
+#
+# @param element Optional root element.
+# @keyparam file Optional file handle or name.  If given, the
+#     tree is initialized with the contents of this XML file.
+
+class ElementTree:
+
+    def __init__(self, element=None, file=None):
+        assert element is None or iselement(element)
+        self._root = element # first node
+        if file:
+            self.parse(file)
+
+    ##
+    # Gets the root element for this tree.
+    #
+    # @return An element instance.
+    # @defreturn Element
+
+    def getroot(self):
+        return self._root
+
+    ##
+    # Replaces the root element for this tree.  This discards the
+    # current contents of the tree, and replaces it with the given
+    # element.  Use with care.
+    #
+    # @param element An element instance.
+
+    def _setroot(self, element):
+        assert iselement(element)
+        self._root = element
+
+    ##
+    # Loads an external XML document into this element tree.
+    #
+    # @param source A file name or file object.
+    # @param parser An optional parser instance.  If not given, the
+    #     standard {@link XMLTreeBuilder} parser is used.
+    # @return The document root element.
+    # @defreturn Element
+
+    def parse(self, source, parser=None):
+        if not hasattr(source, "read"):
+            source = open(source, "rb")
+        if not parser:
+            parser = XMLTreeBuilder()
+        while 1:
+            data = source.read(32768)
+            if not data:
+                break
+            parser.feed(data)
+        self._root = parser.close()
+        return self._root
+
+    ##
+    # Creates a tree iterator for the root element.  The iterator loops
+    # over all elements in this tree, in document order.
+    #
+    # @param tag What tags to look for (default is to return all elements)
+    # @return An iterator.
+    # @defreturn iterator
+
+    def getiterator(self, tag=None):
+        assert self._root is not None
+        return self._root.getiterator(tag)
+
+    ##
+    # Finds the first toplevel element with given tag.
+    # Same as getroot().find(path).
+    #
+    # @param path What element to look for.
+    # @return The first matching element, or None if no element was found.
+    # @defreturn Element or None
+
+    def find(self, path):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+        return self._root.find(path)
+
+    ##
+    # Finds the element text for the first toplevel element with given
+    # tag.  Same as getroot().findtext(path).
+    #
+    # @param path What toplevel element to look for.
+    # @param default What to return if the element was not found.
+    # @return The text content of the first matching element, or the
+    #     default value no element was found.  Note that if the element
+    #     has is found, but has no text content, this method returns an
+    #     empty string.
+    # @defreturn string
+
+    def findtext(self, path, default=None):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+        return self._root.findtext(path, default)
+
+    ##
+    # Finds all toplevel elements with the given tag.
+    # Same as getroot().findall(path).
+    #
+    # @param path What element to look for.
+    # @return A list or iterator containing all matching elements,
+    #    in document order.
+    # @defreturn list of Element instances
+
+    def findall(self, path):
+        assert self._root is not None
+        if path[:1] == "/":
+            path = "." + path
+        return self._root.findall(path)
+
+    ##
+    # Writes the element tree to a file, as XML.
+    #
+    # @param file A file name, or a file object opened for writing.
+    # @param encoding Optional output encoding (default is US-ASCII).
+
+    def write(self, file, encoding="us-ascii"):
+        assert self._root is not None
+        if not hasattr(file, "write"):
+            file = open(file, "wb")
+        if not encoding:
+            encoding = "us-ascii"
+        elif encoding != "utf-8" and encoding != "us-ascii":
+            file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
+        self._write(file, self._root, encoding, {})
+
+    def _write(self, file, node, encoding, namespaces):
+        # write XML to file
+        tag = node.tag
+        if tag is Comment:
+            file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
+        elif tag is ProcessingInstruction:
+            file.write("<?%s?>" % _escape_cdata(node.text, encoding))
+        else:
+            items = node.items()
+            xmlns_items = [] # new namespaces in this scope
+            try:
+                if isinstance(tag, QName) or tag[:1] == "{":
+                    tag, xmlns = fixtag(tag, namespaces)
+                    if xmlns: xmlns_items.append(xmlns)
+            except TypeError:
+                _raise_serialization_error(tag)
+            file.write("<" + _encode(tag, encoding))
+            if items or xmlns_items:
+                items.sort() # lexical order
+                for k, v in items:
+                    try:
+                        if isinstance(k, QName) or k[:1] == "{":
+                            k, xmlns = fixtag(k, namespaces)
+                            if xmlns: xmlns_items.append(xmlns)
+                    except TypeError:
+                        _raise_serialization_error(k)
+                    try:
+                        if isinstance(v, QName):
+                            v, xmlns = fixtag(v, namespaces)
+                            if xmlns: xmlns_items.append(xmlns)
+                    except TypeError:
+                        _raise_serialization_error(v)
+                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
+                                               _escape_attrib(v, encoding)))
+                for k, v in xmlns_items:
+                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
+                                               _escape_attrib(v, encoding)))
+            if node.text or len(node):
+                file.write(">")
+                if node.text:
+                    file.write(_escape_cdata(node.text, encoding))
+                for n in node:
+                    self._write(file, n, encoding, namespaces)
+                file.write("</" + _encode(tag, encoding) + ">")
+            else:
+                file.write(" />")
+            for k, v in xmlns_items:
+                del namespaces[v]
+        if node.tail:
+            file.write(_escape_cdata(node.tail, encoding))
+
+# --------------------------------------------------------------------
+# helpers
+
+##
+# Checks if an object appears to be a valid element object.
+#
+# @param An element instance.
+# @return A true value if this is an element object.
+# @defreturn flag
+
+def iselement(element):
+    # FIXME: not sure about this; might be a better idea to look
+    # for tag/attrib/text attributes
+    return isinstance(element, _ElementInterface) or hasattr(element, "tag")
+
+##
+# Writes an element tree or element structure to sys.stdout.  This
+# function should be used for debugging only.
+# <p>
+# The exact output format is implementation dependent.  In this
+# version, it's written as an ordinary XML file.
+#
+# @param elem An element tree or an individual element.
+
+def dump(elem):
+    # debugging
+    if not isinstance(elem, ElementTree):
+        elem = ElementTree(elem)
+    elem.write(sys.stdout)
+    tail = elem.getroot().tail
+    if not tail or tail[-1] != "\n":
+        sys.stdout.write("\n")
+
+def _encode(s, encoding):
+    try:
+        return s.encode(encoding)
+    except AttributeError:
+        return s # 1.5.2: assume the string uses the right encoding
+
+if sys.version[:3] == "1.5":
+    _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2
+else:
+    _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
+
+_escape_map = {
+    "&": "&amp;",
+    "<": "&lt;",
+    ">": "&gt;",
+    '"': "&quot;",
+}
+
+_namespace_map = {
+    # "well-known" namespace prefixes
+    "http://www.w3.org/XML/1998/namespace": "xml",
+    "http://www.w3.org/1999/xhtml": "html",
+    "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
+    "http://schemas.xmlsoap.org/wsdl/": "wsdl",
+}
+
+def _raise_serialization_error(text):
+    raise TypeError(
+        "cannot serialize %r (type %s)" % (text, type(text).__name__)
+        )
+
+def _encode_entity(text, pattern=_escape):
+    # map reserved and non-ascii characters to numerical entities
+    def escape_entities(m, map=_escape_map):
+        out = []
+        append = out.append
+        for char in m.group():
+            text = map.get(char)
+            if text is None:
+                text = "&#%d;" % ord(char)
+            append(text)
+        return string.join(out, "")
+    try:
+        return _encode(pattern.sub(escape_entities, text), "ascii")
+    except TypeError:
+        _raise_serialization_error(text)
+
+#
+# the following functions assume an ascii-compatible encoding
+# (or "utf-16")
+
+def _escape_cdata(text, encoding=None, replace=string.replace):
+    # escape character data
+    try:
+        if encoding:
+            try:
+                text = _encode(text, encoding)
+            except UnicodeError:
+                return _encode_entity(text)
+        text = replace(text, "&", "&amp;")
+        text = replace(text, "<", "&lt;")
+        text = replace(text, ">", "&gt;")
+        return text
+    except (TypeError, AttributeError):
+        _raise_serialization_error(text)
+
+def _escape_attrib(text, encoding=None, replace=string.replace):
+    # escape attribute value
+    try:
+        if encoding:
+            try:
+                text = _encode(text, encoding)
+            except UnicodeError:
+                return _encode_entity(text)
+        text = replace(text, "&", "&amp;")
+        text = replace(text, "'", "&apos;") # FIXME: overkill
+        text = replace(text, "\"", "&quot;")
+        text = replace(text, "<", "&lt;")
+        text = replace(text, ">", "&gt;")
+        return text
+    except (TypeError, AttributeError):
+        _raise_serialization_error(text)
+
+def fixtag(tag, namespaces):
+    # given a decorated tag (of the form {uri}tag), return prefixed
+    # tag and namespace declaration, if any
+    if isinstance(tag, QName):
+        tag = tag.text
+    namespace_uri, tag = string.split(tag[1:], "}", 1)
+    prefix = namespaces.get(namespace_uri)
+    if prefix is None:
+        prefix = _namespace_map.get(namespace_uri)
+        if prefix is None:
+            prefix = "ns%d" % len(namespaces)
+        namespaces[namespace_uri] = prefix
+        if prefix == "xml":
+            xmlns = None
+        else:
+            xmlns = ("xmlns:%s" % prefix, namespace_uri)
+    else:
+        xmlns = None
+    return "%s:%s" % (prefix, tag), xmlns
+
+##
+# Parses an XML document into an element tree.
+#
+# @param source A filename or file object containing XML data.
+# @param parser An optional parser instance.  If not given, the
+#     standard {@link XMLTreeBuilder} parser is used.
+# @return An ElementTree instance
+
+def parse(source, parser=None):
+    tree = ElementTree()
+    tree.parse(source, parser)
+    return tree
+
+##
+# Parses an XML document into an element tree incrementally, and reports
+# what's going on to the user.
+#
+# @param source A filename or file object containing XML data.
+# @param events A list of events to report back.  If omitted, only "end"
+#     events are reported.
+# @return A (event, elem) iterator.
+
+class iterparse:
+
+    def __init__(self, source, events=None):
+        if not hasattr(source, "read"):
+            source = open(source, "rb")
+        self._file = source
+        self._events = []
+        self._index = 0
+        self.root = self._root = None
+        self._parser = XMLTreeBuilder()
+        # wire up the parser for event reporting
+        parser = self._parser._parser
+        append = self._events.append
+        if events is None:
+            events = ["end"]
+        for event in events:
+            if event == "start":
+                try:
+                    parser.ordered_attributes = 1
+                    parser.specified_attributes = 1
+                    def handler(tag, attrib_in, event=event, append=append,
+                                start=self._parser._start_list):
+                        append((event, start(tag, attrib_in)))
+                    parser.StartElementHandler = handler
+                except AttributeError:
+                    def handler(tag, attrib_in, event=event, append=append,
+                                start=self._parser._start):
+                        append((event, start(tag, attrib_in)))
+                    parser.StartElementHandler = handler
+            elif event == "end":
+                def handler(tag, event=event, append=append,
+                            end=self._parser._end):
+                    append((event, end(tag)))
+                parser.EndElementHandler = handler
+            elif event == "start-ns":
+                def handler(prefix, uri, event=event, append=append):
+                    try:
+                        uri = _encode(uri, "ascii")
+                    except UnicodeError:
+                        pass
+                    append((event, (prefix or "", uri)))
+                parser.StartNamespaceDeclHandler = handler
+            elif event == "end-ns":
+                def handler(prefix, event=event, append=append):
+                    append((event, None))
+                parser.EndNamespaceDeclHandler = handler
+
+    def next(self):
+        while 1:
+            try:
+                item = self._events[self._index]
+            except IndexError:
+                if self._parser is None:
+                    self.root = self._root
+                    try:
+                        raise StopIteration
+                    except NameError:
+                        raise IndexError
+                # load event buffer
+                del self._events[:]
+                self._index = 0
+                data = self._file.read(16384)
+                if data:
+                    self._parser.feed(data)
+                else:
+                    self._root = self._parser.close()
+                    self._parser = None
+            else:
+                self._index = self._index + 1
+                return item
+
+    try:
+        iter
+        def __iter__(self):
+            return self
+    except NameError:
+        def __getitem__(self, index):
+            return self.next()
+
+##
+# Parses an XML document from a string constant.  This function can
+# be used to embed "XML literals" in Python code.
+#
+# @param source A string containing XML data.
+# @return An Element instance.
+# @defreturn Element
+
+def XML(text):
+    parser = XMLTreeBuilder()
+    parser.feed(text)
+    return parser.close()
+
+##
+# Parses an XML document from a string constant, and also returns
+# a dictionary which maps from element id:s to elements.
+#
+# @param source A string containing XML data.
+# @return A tuple containing an Element instance and a dictionary.
+# @defreturn (Element, dictionary)
+
+def XMLID(text):
+    parser = XMLTreeBuilder()
+    parser.feed(text)
+    tree = parser.close()
+    ids = {}
+    for elem in tree.getiterator():
+        id = elem.get("id")
+        if id:
+            ids[id] = elem
+    return tree, ids
+
+##
+# Parses an XML document from a string constant.  Same as {@link #XML}.
+#
+# @def fromstring(text)
+# @param source A string containing XML data.
+# @return An Element instance.
+# @defreturn Element
+
+fromstring = XML
+
+##
+# Generates a string representation of an XML element, including all
+# subelements.
+#
+# @param element An Element instance.
+# @return An encoded string containing the XML data.
+# @defreturn string
+
+def tostring(element, encoding=None):
+    class dummy:
+        pass
+    data = []
+    file = dummy()
+    file.write = data.append
+    ElementTree(element).write(file, encoding)
+    return string.join(data, "")
+
+##
+# Generic element structure builder.  This builder converts a sequence
+# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
+# #TreeBuilder.end} method calls to a well-formed element structure.
+# <p>
+# You can use this class to build an element structure using a custom XML
+# parser, or a parser for some other XML-like format.
+#
+# @param element_factory Optional element factory.  This factory
+#    is called to create new Element instances, as necessary.
+
+class TreeBuilder:
+
+    def __init__(self, element_factory=None):
+        self._data = [] # data collector
+        self._elem = [] # element stack
+        self._last = None # last element
+        self._tail = None # true if we're after an end tag
+        if element_factory is None:
+            element_factory = _ElementInterface
+        self._factory = element_factory
+
+    ##
+    # Flushes the parser buffers, and returns the toplevel documen
+    # element.
+    #
+    # @return An Element instance.
+    # @defreturn Element
+
+    def close(self):
+        assert len(self._elem) == 0, "missing end tags"
+        assert self._last != None, "missing toplevel element"
+        return self._last
+
+    def _flush(self):
+        if self._data:
+            if self._last is not None:
+                text = string.join(self._data, "")
+                if self._tail:
+                    assert self._last.tail is None, "internal error (tail)"
+                    self._last.tail = text
+                else:
+                    assert self._last.text is None, "internal error (text)"
+                    self._last.text = text
+            self._data = []
+
+    ##
+    # Adds text to the current element.
+    #
+    # @param data A string.  This should be either an 8-bit string
+    #    containing ASCII text, or a Unicode string.
+
+    def data(self, data):
+        self._data.append(data)
+
+    ##
+    # Opens a new element.
+    #
+    # @param tag The element name.
+    # @param attrib A dictionary containing element attributes.
+    # @return The opened element.
+    # @defreturn Element
+
+    def start(self, tag, attrs):
+        self._flush()
+        self._last = elem = self._factory(tag, attrs)
+        if self._elem:
+            self._elem[-1].append(elem)
+        self._elem.append(elem)
+        self._tail = 0
+        return elem
+
+    ##
+    # Closes the current element.
+    #
+    # @param tag The element name.
+    # @return The closed element.
+    # @defreturn Element
+
+    def end(self, tag):
+        self._flush()
+        self._last = self._elem.pop()
+        assert self._last.tag == tag,\
+               "end tag mismatch (expected %s, got %s)" % (
+                   self._last.tag, tag)
+        self._tail = 1
+        return self._last
+
+##
+# Element structure builder for XML source data, based on the
+# <b>expat</b> parser.
+#
+# @keyparam target Target object.  If omitted, the builder uses an
+#     instance of the standard {@link #TreeBuilder} class.
+# @keyparam html Predefine HTML entities.  This flag is not supported
+#     by the current implementation.
+# @see #ElementTree
+# @see #TreeBuilder
+
+class XMLTreeBuilder:
+
+    def __init__(self, html=0, target=None):
+        try:
+            from xmlcore.parsers import expat
+        except ImportError:
+            raise ImportError(
+                "No module named expat; use SimpleXMLTreeBuilder instead"
+                )
+        self._parser = parser = expat.ParserCreate(None, "}")
+        if target is None:
+            target = TreeBuilder()
+        self._target = target
+        self._names = {} # name memo cache
+        # callbacks
+        parser.DefaultHandlerExpand = self._default
+        parser.StartElementHandler = self._start
+        parser.EndElementHandler = self._end
+        parser.CharacterDataHandler = self._data
+        # let expat do the buffering, if supported
+        try:
+            self._parser.buffer_text = 1
+        except AttributeError:
+            pass
+        # use new-style attribute handling, if supported
+        try:
+            self._parser.ordered_attributes = 1
+            self._parser.specified_attributes = 1
+            parser.StartElementHandler = self._start_list
+        except AttributeError:
+            pass
+        encoding = None
+        if not parser.returns_unicode:
+            encoding = "utf-8"
+        # target.xml(encoding, None)
+        self._doctype = None
+        self.entity = {}
+
+    def _fixtext(self, text):
+        # convert text string to ascii, if possible
+        try:
+            return _encode(text, "ascii")
+        except UnicodeError:
+            return text
+
+    def _fixname(self, key):
+        # expand qname, and convert name string to ascii, if possible
+        try:
+            name = self._names[key]
+        except KeyError:
+            name = key
+            if "}" in name:
+                name = "{" + name
+            self._names[key] = name = self._fixtext(name)
+        return name
+
+    def _start(self, tag, attrib_in):
+        fixname = self._fixname
+        tag = fixname(tag)
+        attrib = {}
+        for key, value in attrib_in.items():
+            attrib[fixname(key)] = self._fixtext(value)
+        return self._target.start(tag, attrib)
+
+    def _start_list(self, tag, attrib_in):
+        fixname = self._fixname
+        tag = fixname(tag)
+        attrib = {}
+        if attrib_in:
+            for i in range(0, len(attrib_in), 2):
+                attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
+        return self._target.start(tag, attrib)
+
+    def _data(self, text):
+        return self._target.data(self._fixtext(text))
+
+    def _end(self, tag):
+        return self._target.end(self._fixname(tag))
+
+    def _default(self, text):
+        prefix = text[:1]
+        if prefix == "&":
+            # deal with undefined entities
+            try:
+                self._target.data(self.entity[text[1:-1]])
+            except KeyError:
+                from xmlcore.parsers import expat
+                raise expat.error(
+                    "undefined entity %s: line %d, column %d" %
+                    (text, self._parser.ErrorLineNumber,
+                    self._parser.ErrorColumnNumber)
+                    )
+        elif prefix == "<" and text[:9] == "<!DOCTYPE":
+            self._doctype = [] # inside a doctype declaration
+        elif self._doctype is not None:
+            # parse doctype contents
+            if prefix == ">":
+                self._doctype = None
+                return
+            text = string.strip(text)
+            if not text:
+                return
+            self._doctype.append(text)
+            n = len(self._doctype)
+            if n > 2:
+                type = self._doctype[1]
+                if type == "PUBLIC" and n == 4:
+                    name, type, pubid, system = self._doctype
+                elif type == "SYSTEM" and n == 3:
+                    name, type, system = self._doctype
+                    pubid = None
+                else:
+                    return
+                if pubid:
+                    pubid = pubid[1:-1]
+                self.doctype(name, pubid, system[1:-1])
+                self._doctype = None
+
+    ##
+    # Handles a doctype declaration.
+    #
+    # @param name Doctype name.
+    # @param pubid Public identifier.
+    # @param system System identifier.
+
+    def doctype(self, name, pubid, system):
+        pass
+
+    ##
+    # Feeds data to the parser.
+    #
+    # @param data Encoded data.
+
+    def feed(self, data):
+        self._parser.Parse(data, 0)
+
+    ##
+    # Finishes feeding data to the parser.
+    #
+    # @return An element structure.
+    # @defreturn Element
+
+    def close(self):
+        self._parser.Parse("", 1) # end of data
+        tree = self._target.close()
+        del self._target, self._parser # get rid of circular references
+        return tree
index ef8d14cdb0483ae8ec25d8977bf0228458ff2502..cef1a6bba16a7597ac2b8caabdcb3072715fa6a1 100644 (file)
@@ -1,30 +1,30 @@
-# $Id: __init__.py 1821 2004-06-03 16:57:49Z fredrik $\r
-# elementtree package\r
-\r
-# --------------------------------------------------------------------\r
-# The ElementTree toolkit is\r
-#\r
-# Copyright (c) 1999-2004 by Fredrik Lundh\r
-#\r
-# By obtaining, using, and/or copying this software and/or its\r
-# associated documentation, you agree that you have read, understood,\r
-# and will comply with the following terms and conditions:\r
-#\r
-# Permission to use, copy, modify, and distribute this software and\r
-# its associated documentation for any purpose and without fee is\r
-# hereby granted, provided that the above copyright notice appears in\r
-# all copies, and that both that copyright notice and this permission\r
-# notice appear in supporting documentation, and that the name of\r
-# Secret Labs AB or the author not be used in advertising or publicity\r
-# pertaining to distribution of the software without specific, written\r
-# prior permission.\r
-#\r
-# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\r
-# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\r
-# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR\r
-# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\r
-# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\r
-# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\r
-# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\r
-# OF THIS SOFTWARE.\r
-# --------------------------------------------------------------------\r
+# $Id: __init__.py 1821 2004-06-03 16:57:49Z fredrik $
+# elementtree package
+
+# --------------------------------------------------------------------
+# The ElementTree toolkit is
+#
+# Copyright (c) 1999-2004 by Fredrik Lundh
+#
+# By obtaining, using, and/or copying this software and/or its
+# associated documentation, you agree that you have read, understood,
+# and will comply with the following terms and conditions:
+#
+# Permission to use, copy, modify, and distribute this software and
+# its associated documentation for any purpose and without fee is
+# hereby granted, provided that the above copyright notice appears in
+# all copies, and that both that copyright notice and this permission
+# notice appear in supporting documentation, and that the name of
+# Secret Labs AB or the author not be used in advertising or publicity
+# pertaining to distribution of the software without specific, written
+# prior permission.
+#
+# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
+# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
+# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
+# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+# OF THIS SOFTWARE.
+# --------------------------------------------------------------------