Python elementtree.ElementTree.ElementTree() Examples

The following are 30 code examples of elementtree.ElementTree.ElementTree(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module elementtree.ElementTree , or try the search function .
Example #1
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def writetext(self, elem, compact=0):
        if len(elem):
            if compact and len(elem) == 1 and elem[0].tag == "p":
                elem = elem[0]
                self.file.write(html_encode(elem.text))
                for e in elem:
                    ET.ElementTree(e).write(self.file)
                self.file.write(html_encode(elem.tail))
            else:
                for e in elem:
                    ET.ElementTree(e).write(self.file)
        elif elem is not None and elem.text:
            if compact:
                self.file.write(html_encode(elem.text))
            else:
                self.file.write("<p>%s</p>\n" % html_encode(elem.text))

    ##
    # Writes an object description (the description text, parameters,
    # return values) etc.
    #
    # @param object The object element.
    # @param summary If true, use summary instead of full description. 
Example #2
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def unknown_endtag(self, tag):
            self.handle_endtag(tag)

##
# ElementTree builder for HTML source code.  This builder converts an
# HTML document or fragment to an ElementTree.
# <p>
# The parser is relatively picky, and requires balanced tags for most
# elements.  However, elements belonging to the following group are
# automatically closed: P, LI, TR, TH, and TD.  In addition, the
# parser automatically inserts end tags immediately after the start
# tag, and ignores any end tags for the following group: IMG, HR,
# META, and LINK.
#
# @keyparam builder Optional builder object.  If omitted, the parser
#     uses the standard <b>elementtree</b> builder.
# @keyparam encoding Optional character encoding, if known.  If omitted,
#     the parser looks for META tags inside the document.  If no tags
#     are found, the parser defaults to ISO-8859-1.  Note that if your
#     document uses a non-ASCII compatible encoding, you must decode
#     the document before parsing. 
Example #3
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def writetext(self, elem, compact=0):
        if len(elem):
            if compact and len(elem) == 1 and elem[0].tag == "p":
                elem = elem[0]
                self.file.write(html_encode(elem.text))
                for e in elem:
                    ET.ElementTree(e).write(self.file)
                self.file.write(html_encode(elem.tail))
            else:
                for e in elem:
                    ET.ElementTree(e).write(self.file)
        elif elem is not None and elem.text:
            if compact:
                self.file.write(html_encode(elem.text))
            else:
                self.file.write("<p>%s</p>\n" % html_encode(elem.text))

    ##
    # Writes an object description (the description text, parameters,
    # return values) etc.
    #
    # @param object The object element.
    # @param summary If true, use summary instead of full description. 
Example #4
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def unknown_endtag(self, tag):
            self.handle_endtag(tag)

##
# ElementTree builder for HTML source code.  This builder converts an
# HTML document or fragment to an ElementTree.
# <p>
# The parser is relatively picky, and requires balanced tags for most
# elements.  However, elements belonging to the following group are
# automatically closed: P, LI, TR, TH, and TD.  In addition, the
# parser automatically inserts end tags immediately after the start
# tag, and ignores any end tags for the following group: IMG, HR,
# META, and LINK.
#
# @keyparam builder Optional builder object.  If omitted, the parser
#     uses the standard <b>elementtree</b> builder.
# @keyparam encoding Optional character encoding, if known.  If omitted,
#     the parser looks for META tags inside the document.  If no tags
#     are found, the parser defaults to ISO-8859-1.  Note that if your
#     document uses a non-ASCII compatible encoding, you must decode
#     the document before parsing. 
Example #5
Source File: selftest.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def entity():
    """
    Test entity handling.

    1) bad entities

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

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

    (add more tests here)

    """ 
Example #6
Source File: selftest.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def parsefile():
    """
    Test parsing from file.

    >>> tree = ElementTree.parse("samples/simple.xml")
    >>> normalize_crlf(tree)
    >>> tree.write(sys.stdout)
    <root>
       <element key="value">text</element>
       <element>text</element>tail
       <empty-element />
    </root>
    >>> tree = ElementTree.parse("samples/simple-ns.xml")
    >>> normalize_crlf(tree)
    >>> tree.write(sys.stdout)
    <ns0:root xmlns:ns0="namespace">
       <ns0:element key="value">text</ns0:element>
       <ns0:element>text</ns0:element>tail
       <ns0:empty-element />
    </ns0:root>
    """ 
Example #7
Source File: selftest.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def parseliteral():
    r"""
    >>> element = ElementTree.XML("<html><body>text</body></html>")
    >>> ElementTree.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> element = ElementTree.fromstring("<html><body>text</body></html>")
    >>> ElementTree.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> print ElementTree.tostring(element)
    <html><body>text</body></html>
    >>> print ElementTree.tostring(element, "ascii")
    <?xml version='1.0' encoding='ascii'?>
    <html><body>text</body></html>
    >>> _, ids = ElementTree.XMLID("<html><body>text</body></html>")
    >>> len(ids)
    0
    >>> _, ids = ElementTree.XMLID("<html><body id='body'>text</body></html>")
    >>> len(ids)
    1
    >>> ids["body"].tag
    'body'
    """ 
Example #8
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def simpleparsefile():
    """
    Test the xmllib-based parser.

    >>> from elementtree import SimpleXMLTreeBuilder
    >>> parser = SimpleXMLTreeBuilder.TreeBuilder()
    >>> tree = ElementTree.parse("samples/simple.xml", parser)
    >>> normalize_crlf(tree)
    >>> tree.write(sys.stdout)
    <root>
       <element key="value">text</element>
       <element>text</element>tail
       <empty-element />
    </root>
    """ 
Example #9
Source File: __init__.py    From aws-extender with MIT License 5 votes vote down vote up
def create_manifest(self):
        if WhichElementTree == 'lxml':
            root = Element('manifest:manifest',
                nsmap=MANIFEST_NAMESPACE_DICT,
                nsdict=MANIFEST_NAMESPACE_DICT,
                )
        else:
            root = Element('manifest:manifest',
                attrib=MANIFEST_NAMESPACE_ATTRIB,
                nsdict=MANIFEST_NAMESPACE_DICT,
                )
        doc = etree.ElementTree(root)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': self.MIME_TYPE,
            'manifest:full-path': '/',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'content.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'styles.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'settings.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'meta.xml',
            }, nsdict=MANNSD)
        s1 = ToString(doc)
        doc = minidom.parseString(s1)
        s1 = doc.toprettyxml('  ')
        return s1 
Example #10
Source File: __init__.py    From aws-extender with MIT License 5 votes vote down vote up
def astext(self):
        root = self.content_tree.getroot()
        et = etree.ElementTree(root)
        s1 = ToString(et)
        return s1 
Example #11
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def serialize(elem, encoding=None):
    import cStringIO
    file = cStringIO.StringIO()
    tree = ElementTree.ElementTree(elem)
    if encoding:
        tree.write(file, encoding)
    else:
        tree.write(file)
    return file.getvalue() 
Example #12
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def sanity():
    """
    >>> from elementtree.ElementTree import *
    >>> from elementtree.ElementInclude import *
    >>> from elementtree.ElementPath import *
    >>> from elementtree.HTMLTreeBuilder import *
    >>> from elementtree.SimpleXMLTreeBuilder import *
    >>> from elementtree.SimpleXMLWriter import *
    >>> from elementtree.TidyTools import *
    >>> from elementtree.XMLTreeBuilder import *
    """ 
Example #13
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def version():
    """
    >>> ElementTree.VERSION
    '1.2.7'
    """ 
Example #14
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def interface():
    """
    Test element tree interface.

    >>> element = ElementTree.Element("tag")
    >>> check_element(element)
    >>> tree = ElementTree.ElementTree(element)
    >>> check_element_tree(tree)
    """ 
Example #15
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def simplefind():
    """
    Test find methods using the elementpath fallback.

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

    Path syntax doesn't work in this case.

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

    >>> ElementTree.ElementPath = CurrentElementPath
    """ 
Example #16
Source File: __init__.py    From blackmamba with MIT License 5 votes vote down vote up
def astext(self):
        root = self.content_tree.getroot()
        et = etree.ElementTree(root)
        s1 = ToString(et)
        return s1 
Example #17
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def fancyparsefile():
    """
    Test the "fancy" parser.

    Sanity check.
    >>> from elementtree import XMLTreeBuilder
    >>> parser = XMLTreeBuilder.FancyTreeBuilder()
    >>> tree = ElementTree.parse("samples/simple.xml", parser)
    >>> normalize_crlf(tree)
    >>> tree.write(sys.stdout)
    <root>
       <element key="value">text</element>
       <element>text</element>tail
       <empty-element />
    </root>

    Callback check.
    >>> class MyFancyParser(XMLTreeBuilder.FancyTreeBuilder):
    ...     def start(self, elem):
    ...         print "START", elem.tag
    ...     def end(self, elem):
    ...         print "END", elem.tag
    >>> parser = MyFancyParser()
    >>> tree = ElementTree.parse("samples/simple.xml", parser)
    START root
    START element
    END element
    START element
    END element
    START empty-element
    END empty-element
    END root
    """ 
Example #18
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def writefile():
    """
    >>> elem = ElementTree.Element("tag")
    >>> elem.text = "text"
    >>> serialize(elem)
    '<tag>text</tag>'
    >>> ElementTree.SubElement(elem, "subtag").text = "subtext"
    >>> serialize(elem)
    '<tag>text<subtag>subtext</subtag></tag>'
    """ 
Example #19
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def namespace():
    """
    Test namespace issues.

    1) xml namespace

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

    2) other "well-known" namespaces

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

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

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

    3) unknown namespaces

    """ 
Example #20
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def xinclude_loader(href, parse="xml", encoding=None):
    try:
        data = XINCLUDE[href]
    except KeyError:
        raise IOError("resource not found")
    if parse == "xml":
        return ElementTree.XML(data)
    return data 
Example #21
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkit21():
    """
    marshaller gives obscure errors for non-string values

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

    """ 
Example #22
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkit28():
    """
    .//tag causes exceptions

    >>> tree = ElementTree.XML("<doc><table><tbody/></table></doc>")
    >>> summarize_list(tree.findall(".//thead"))
    []
    >>> summarize_list(tree.findall(".//tbody"))
    ['tbody']
    """ 
Example #23
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkitX1():
    """
    dump() doesn't flush the output buffer

    >>> tree = ElementTree.XML("<doc><table><tbody/></table></doc>")
    >>> ElementTree.dump(tree); sys.stdout.write("tail")
    <doc><table><tbody /></table></doc>
    tail
    """ 
Example #24
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkit39():
    """
    non-ascii element and attribute names doesn't work

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

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

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

    >>> tree = ElementTree.Element(u"t�g")
    >>> ElementTree.tostring(tree, "utf-8")
    '<t\\xc3\\xa4g />'

    >>> tree = ElementTree.Element("tag")
    >>> tree.set(u"�ttr", u"v�lue")
    >>> ElementTree.tostring(tree, "utf-8")
    '<tag \\xc3\\xa4ttr="v\\xc3\\xa4lue" />'

    """ 
Example #25
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkit54():
    """
    problems handling internally defined entities

    >>> e = ElementTree.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]><doc>&ldots;</doc>")
    >>> serialize(e)
    '<doc>&#33328;</doc>'
    """ 
Example #26
Source File: selftest.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def bug_xmltoolkit55():
    """
    make sure we're reporting the first error, not the last

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

# -------------------------------------------------------------------- 
Example #27
Source File: __init__.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def create_manifest(self):
        if WhichElementTree == 'lxml':
            root = Element(
                'manifest:manifest',
                nsmap=MANIFEST_NAMESPACE_DICT,
                nsdict=MANIFEST_NAMESPACE_DICT,
            )
        else:
            root = Element(
                'manifest:manifest',
                attrib=MANIFEST_NAMESPACE_ATTRIB,
                nsdict=MANIFEST_NAMESPACE_DICT,
            )
        doc = etree.ElementTree(root)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': self.MIME_TYPE,
            'manifest:full-path': '/',
        }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'content.xml',
        }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'styles.xml',
        }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'settings.xml',
        }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'meta.xml',
        }, nsdict=MANNSD)
        s1 = ToString(doc)
        doc = minidom.parseString(s1)
        s1 = doc.toprettyxml('  ')
        return s1 
Example #28
Source File: __init__.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def astext(self):
        root = self.content_tree.getroot()
        et = etree.ElementTree(root)
        s1 = ToString(et)
        return s1 
Example #29
Source File: __init__.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def astext(self):
        root = self.content_tree.getroot()
        et = etree.ElementTree(root)
        s1 = ToString(et)
        return s1 
Example #30
Source File: settings.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def get_field_marker_hierarchy(self) :
        # Find root field marker
        root = None
        for fm in self.get_markers() :
            fmmd = self.get_metadata_by_marker(fm)            
            if not fmmd.get_parent_marker() :
                root = fm

        # Build tree for field markers
        builder = ElementTree.TreeBuilder()
        builder.start(root, {})
        self.build_tree(root, builder)
        builder.end(root)
        return ElementTree.ElementTree(builder.close())