Python xml.etree.ElementTree.TreeBuilder() Examples

The following are 30 code examples of xml.etree.ElementTree.TreeBuilder(). 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 xml.etree.ElementTree , or try the search function .
Example #1
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, quiet=False):
        if sys.flags.optimize >= 2:
            # under -OO, doctests cannot be run and therefore not all warnings
            # will be emitted
            quiet = True
        deprecations = (
            # Search behaviour is broken if search path starts with "/".
            ("This search is broken in 1.3 and earlier, and will be fixed "
             "in a future version.  If you rely on the current behaviour, "
             "change it to '.+'", FutureWarning),
            # Element.getchildren() and Element.getiterator() are deprecated.
            ("This method will be removed in future versions.  "
             "Use .+ instead.", DeprecationWarning),
            ("This method will be removed in future versions.  "
             "Use .+ instead.", PendingDeprecationWarning),
            # XMLParser.doctype() is deprecated.
            ("This method of XMLParser is deprecated.  Define doctype.. "
             "method on the TreeBuilder target.", DeprecationWarning))
        self.checkwarnings = test_support.check_warnings(*deprecations,
                                                         quiet=quiet) 
Example #2
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def xmltoolkit63():
    """

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

    """
    tree = ET.TreeBuilder()
    tree.start("tag", {})
    tree.data("text")
    tree.end("tag")

# -------------------------------------------------------------------- 
Example #3
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, quiet=False):
        if sys.flags.optimize >= 2:
            # under -OO, doctests cannot be run and therefore not all warnings
            # will be emitted
            quiet = True
        deprecations = (
            # Search behaviour is broken if search path starts with "/".
            ("This search is broken in 1.3 and earlier, and will be fixed "
             "in a future version.  If you rely on the current behaviour, "
             "change it to '.+'", FutureWarning),
            # Element.getchildren() and Element.getiterator() are deprecated.
            ("This method will be removed in future versions.  "
             "Use .+ instead.", DeprecationWarning),
            ("This method will be removed in future versions.  "
             "Use .+ instead.", PendingDeprecationWarning),
            # XMLParser.doctype() is deprecated.
            ("This method of XMLParser is deprecated.  Define doctype.. "
             "method on the TreeBuilder target.", DeprecationWarning))
        self.checkwarnings = test_support.check_warnings(*deprecations,
                                                         quiet=quiet) 
Example #4
Source File: gdal2tiles.py    From gdal2tiles with MIT License 6 votes vote down vote up
def add_gdal_warp_options_to_string(vrt_string, warp_options):
    if not warp_options:
        return vrt_string

    vrt_root = ElementTree.fromstring(vrt_string)
    options = vrt_root.find("GDALWarpOptions")

    if options is None:
        return vrt_string

    for key, value in warp_options.items():
        tb = ElementTree.TreeBuilder()
        tb.start("Option", {"name": key})
        tb.data(value)
        tb.end("Option")
        elem = tb.close()
        options.insert(0, elem)

    return ElementTree.tostring(vrt_root).decode() 
Example #5
Source File: gdal2tiles.py    From gdal2tiles with MIT License 6 votes vote down vote up
def add_gdal_warp_options_to_string(vrt_string, warp_options):
    if not warp_options:
        return vrt_string

    vrt_root = ElementTree.fromstring(vrt_string)
    options = vrt_root.find("GDALWarpOptions")

    if options is None:
        return vrt_string

    for key, value in warp_options.items():
        tb = ElementTree.TreeBuilder()
        tb.start("Option", {"name": key})
        tb.data(value)
        tb.end("Option")
        elem = tb.close()
        options.insert(0, elem)

    return ElementTree.tostring(vrt_root).decode() 
Example #6
Source File: xml_cli.py    From compas with MIT License 6 votes vote down vote up
def __init__(self, target=None, validating=False):
        if not compas.is_ironpython():
            raise Exception('CLRXMLTreeParser can only be used from IronPython')

        settings = XmlReaderSettings()
        settings.IgnoreComments = True
        settings.IgnoreProcessingInstructions = True
        settings.IgnoreWhitespace = True
        if not validating:
            settings.DtdProcessing = DtdProcessing.Ignore
            settings.ValidationType = getattr(ValidationType, 'None')
        else:
            settings.DtdProcessing = DtdProcessing.Parse
            settings.ValidationType = ValidationType.DTD
        self.settings = settings
        self._target = (target if (target is not None) else ET.TreeBuilder())
        self._buffer = []
        self._document_encoding = 'UTF-8'  # default 
Example #7
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def xmltoolkit63():
    """

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

    """
    tree = ET.TreeBuilder()
    tree.start("tag", {})
    tree.data("text")
    tree.end("tag")

# -------------------------------------------------------------------- 
Example #8
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def __init__(self, quiet=False):
        if sys.flags.optimize >= 2:
            # under -OO, doctests cannot be run and therefore not all warnings
            # will be emitted
            quiet = True
        deprecations = (
            # Search behaviour is broken if search path starts with "/".
            ("This search is broken in 1.3 and earlier, and will be fixed "
             "in a future version.  If you rely on the current behaviour, "
             "change it to '.+'", FutureWarning),
            # Element.getchildren() and Element.getiterator() are deprecated.
            ("This method will be removed in future versions.  "
             "Use .+ instead.", DeprecationWarning),
            ("This method will be removed in future versions.  "
             "Use .+ instead.", PendingDeprecationWarning),
            # XMLParser.doctype() is deprecated.
            ("This method of XMLParser is deprecated.  Define doctype.. "
             "method on the TreeBuilder target.", DeprecationWarning))
        self.checkwarnings = test_support.check_warnings(*deprecations,
                                                         quiet=quiet) 
Example #9
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def xmltoolkit63():
    """

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

    """
    tree = ET.TreeBuilder()
    tree.start("tag", {})
    tree.data("text")
    tree.end("tag")

# -------------------------------------------------------------------- 
Example #10
Source File: read.py    From typhon with MIT License 6 votes vote down vote up
def parse(source, binaryfp=None):
    """Parse ArtsXML file from source.

    Args:
        source (str): Filename or file pointer.

    Returns:
        xml.etree.ElementTree: XML Tree of the ARTS data file.

    """
    arts_element = type('ARTSElementBinaryFP',
                        ARTSElement.__bases__,
                        dict(ARTSElement.__dict__))
    arts_element.binaryfp = binaryfp
    return ElementTree.parse(source,
                             parser=ElementTree.XMLParser(
                                 target=ElementTree.TreeBuilder(
                                     element_factory=arts_element))) 
Example #11
Source File: merge_xml.py    From se-blender with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, target=None, encoding=None):
        try:
            from xml.parsers import expat
        except ImportError:
            try:
                import pyexpat as expat
            except ImportError:
                raise ImportError(
                    "No module named expat; use SimpleXMLTreeBuilder instead"
                    )
        parser = expat.ParserCreate(encoding, "}")
        if target is None:
            target = ET.TreeBuilder()
        self.parser = parser
        self.target = target
        self._error = expat.error
        self._names = {} # name memo cache
        # main callbacks
        parser.DefaultHandlerExpand = self._default
        if hasattr(target, 'start'):
            parser.StartElementHandler = self._start
        if hasattr(target, 'end'):
            parser.EndElementHandler = self._end
        if hasattr(target, 'data'):
            parser.CharacterDataHandler = target.data
        if hasattr(target, 'comment'):
            parser.CommentHandler = target.comment
        if hasattr(target, 'pi'):
            parser.ProcessingInstructionHandler = target.pi
        # Configure pyexpat: buffering, new-style attribute handling.
        parser.buffer_text = 1
        parser.ordered_attributes = 1
        parser.specified_attributes = 1
        self._doctype = None
        self.entity = {}
        try:
            self.version = "Expat %d.%d.%d" % expat.version_info
        except AttributeError:
            pass # unknown 
Example #12
Source File: toolbox.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def parse(self, encoding=None, errors='strict', **kwargs):
        """
        Return the contents of toolbox settings file with a nested structure.

        :param encoding: encoding used by settings file
        :type encoding: str
        :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method.
        :type errors: str
        :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
        :type kwargs: dict
        :rtype: ElementTree._ElementInterface
        """
        builder = TreeBuilder()
        for mkr, value in self.fields(encoding=encoding, errors=errors, **kwargs):
            # Check whether the first char of the field marker
            # indicates a block start (+) or end (-)
            block = mkr[0]
            if block in ("+", "-"):
                mkr = mkr[1:]
            else:
                block = None
            # Build tree on the basis of block char
            if block == "+":
                builder.start(mkr, {})
                builder.data(value)
            elif block == '-':
                builder.end(mkr)
            else:
                builder.start(mkr, {})
                builder.data(value)
                builder.end(mkr)
        return builder.close() 
Example #13
Source File: io_08.py    From Modern-Python-Standard-Library-Cookbook with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ETHTMLParser, self).__init__(*args, **kwargs)
        self._builder = ET.TreeBuilder()
        self._stack = [] 
Example #14
Source File: subscriptions.py    From castero with MIT License 5 votes vote down vote up
def generate(self, feeds: List[Feed]) -> None:
        """Create subscriptions document from list of feeds.

        Args:
            feeds: the list of feeds to include in the document
        """
        builder = ElementTree.TreeBuilder()

        builder.start("opml", {'version': '2.0'})
        builder.start("head", {})
        builder.start("title", {})
        builder.data("castero feeds")
        builder.end("title")
        builder.end("head")
        builder.start("body", {})
        for feed in feeds:
            builder.start("outline", {
                'type': 'rss',
                'text': str(feed),
                'xmlUrl': feed.key
            })
            builder.end("outline")
        builder.end("body")
        builder.end("opml")

        # .close returns an Element, so we need to cast to an ElementTree
        self._tree = ElementTree.ElementTree(builder.close()) 
Example #15
Source File: process_local_docs.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.tree_builder = ElementTree.TreeBuilder()
    self.tree = None 
Example #16
Source File: __init__.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, partial=False, _parsetree_roundtrip=False):
		self.partial = partial
		self._b = ElementTreeModule.TreeBuilder()
		self.stack = [] #: keeps track of current open elements
		self._last_char = None
		self._parsetree_roundtrip = _parsetree_roundtrip 
Example #17
Source File: support.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def message(self):
        builder = TreeBuilder()
        builder.start(self.resource_type, dict())
        self.serialize(builder)
        builder.end(self.resource_type)
        msg = tostring(builder.close())
        return msg 
Example #18
Source File: toolbox.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def parse(self, encoding=None, errors='strict', **kwargs):
        """
        Return the contents of toolbox settings file with a nested structure.

        :param encoding: encoding used by settings file
        :type encoding: str
        :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method.
        :type errors: str
        :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
        :type kwargs: dict
        :rtype: ElementTree._ElementInterface
        """
        builder = TreeBuilder()
        for mkr, value in self.fields(encoding=encoding, errors=errors, **kwargs):
            # Check whether the first char of the field marker
            # indicates a block start (+) or end (-)
            block=mkr[0]
            if block in ("+", "-"):
                mkr=mkr[1:]
            else:
                block=None
            # Build tree on the basis of block char
            if block == "+":
                builder.start(mkr, {})
                builder.data(value)
            elif block == '-':
                builder.end(mkr)
            else:
                builder.start(mkr, {})
                builder.data(value)
                builder.end(mkr)
        return builder.close() 
Example #19
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bug_1534630():
    """

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

    """ 
Example #20
Source File: toolbox.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def parse(self, encoding=None, errors='strict', **kwargs):
        """
        Return the contents of toolbox settings file with a nested structure.

        :param encoding: encoding used by settings file
        :type encoding: str
        :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method.
        :type errors: str
        :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
        :type kwargs: dict
        :rtype: ElementTree._ElementInterface
        """
        builder = TreeBuilder()
        for mkr, value in self.fields(encoding=encoding, errors=errors, **kwargs):
            # Check whether the first char of the field marker
            # indicates a block start (+) or end (-)
            block=mkr[0]
            if block in ("+", "-"):
                mkr=mkr[1:]
            else:
                block=None
            # Build tree on the basis of block char
            if block == "+":
                builder.start(mkr, {})
                builder.data(value)
            elif block == '-':
                builder.end(mkr)
            else:
                builder.start(mkr, {})
                builder.data(value)
                builder.end(mkr)
        return builder.close() 
Example #21
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 5 votes vote down vote up
def __init__(self, encoding=None):
        self.__stack = []
        self.__builder = ET.TreeBuilder()
        self.encoding = encoding or "iso-8859-1"
        HTMLParser.__init__(self)

    ##
    # Flushes parser buffers, and return the root element.
    #
    # @return An Element instance. 
Example #22
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 5 votes vote down vote up
def __init__(self, encoding=None):
        self.__stack = []
        self.__builder = ET.TreeBuilder()
        self.encoding = encoding or "iso-8859-1"
        HTMLParser.__init__(self)

    ##
    # Flushes parser buffers, and return the root element.
    #
    # @return An Element instance. 
Example #23
Source File: xml_util.py    From pyxcli with Apache License 2.0 5 votes vote down vote up
def end(self, tag):
        element = et.TreeBuilder.end(self, tag)
        if self.root_element is element:
            self.root_element_closed = True
        return element 
Example #24
Source File: xml_util.py    From pyxcli with Apache License 2.0 5 votes vote down vote up
def start(self, tag, attrs):
        element = et.TreeBuilder.start(self, tag, attrs)
        if self.root_element is None:
            self.root_element = element
        return element 
Example #25
Source File: xml_util.py    From pyxcli with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        et.TreeBuilder.__init__(self)
        self.root_element = None
        self.root_element_closed = False 
Example #26
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
def bug_1534630():
    """

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

    """ 
Example #27
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
def bug_1534630():
    """

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

    """ 
Example #28
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def parsefile():
    """
    Test parsing from file.

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

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

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

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

    >>> target = ET.TreeBuilder()
    >>> parser = ET.XMLParser(target=target)
    >>> parser.feed(data)
    >>> print serialize(parser.close())
    <root>
       <element key="value">text</element>
       <element>text</element>tail
       <empty-element />
    </root>
    """ 
Example #29
Source File: stub_dispatcher.py    From python-compat-runtime with Apache License 2.0 4 votes vote down vote up
def _handle_get(gcs_stub, filename, param_dict, headers):
  """Handle GET object and GET bucket."""
  mo = re.match(BUCKET_ONLY_PATH, filename)
  if mo is not None:

    if 'location' in param_dict:
      builder = ET.TreeBuilder()
      builder.start('LocationConstraint', {})
      builder.data('US')
      builder.end('LocationConstraint')
      root = builder.close()
      body = ET.tostring(root)
      response_headers = {'content-length': len(body),
                          'content-type': 'application/xml'}
      return _FakeUrlFetchResult(httplib.OK, response_headers, body)
    elif 'storageClass' in param_dict:
      builder = ET.TreeBuilder()
      builder.start('StorageClass', {})
      builder.data('STANDARD')
      builder.end('StorageClass')
      root = builder.close()
      body = ET.tostring(root)
      response_headers = {'content-length': len(body),
                          'content-type': 'application/xml'}
      return _FakeUrlFetchResult(httplib.OK, response_headers, body)
    else:

      return _handle_get_bucket(gcs_stub, mo.group(1), param_dict)
  else:

    result = _handle_head(gcs_stub, filename)
    if result.status_code == httplib.NOT_FOUND:
      return result



    start, end = _Range(headers).value
    st_size = result.headers['x-goog-stored-content-length']
    if end is not None:
      result.status_code = httplib.PARTIAL_CONTENT
      end = min(end, st_size - 1)
      result.headers['content-range'] = 'bytes %d-%d/%d' % (start, end, st_size)

    result.content = gcs_stub.get_object(filename, start, end)
    result.headers['content-length'] = len(result.content)
    return result 
Example #30
Source File: gdal2tiles.py    From gdal2tiles with MIT License 4 votes vote down vote up
def add_alpha_band_to_string_vrt(vrt_string):
    # TODO: gbataille - Old code speak of this being equivalent to gdalwarp -dstalpha
    # To be checked

    vrt_root = ElementTree.fromstring(vrt_string)

    index = 0
    nb_bands = 0
    for subelem in list(vrt_root):
        if subelem.tag == "VRTRasterBand":
            nb_bands += 1
            color_node = subelem.find("./ColorInterp")
            if color_node is not None and color_node.text == "Alpha":
                raise Exception("Alpha band already present")
        else:
            if nb_bands:
                # This means that we are one element after the Band definitions
                break

        index += 1

    tb = ElementTree.TreeBuilder()
    tb.start("VRTRasterBand",
             {'dataType': "Byte", "band": str(nb_bands + 1), "subClass": "VRTWarpedRasterBand"})
    tb.start("ColorInterp", {})
    tb.data("Alpha")
    tb.end("ColorInterp")
    tb.end("VRTRasterBand")
    elem = tb.close()

    vrt_root.insert(index, elem)

    warp_options = vrt_root.find(".//GDALWarpOptions")
    tb = ElementTree.TreeBuilder()
    tb.start("DstAlphaBand", {})
    tb.data(str(nb_bands + 1))
    tb.end("DstAlphaBand")
    elem = tb.close()
    warp_options.append(elem)

    # TODO: gbataille - this is a GDALWarpOptions. Why put it in a specific place?
    tb = ElementTree.TreeBuilder()
    tb.start("Option", {"name": "INIT_DEST"})
    tb.data("0")
    tb.end("Option")
    elem = tb.close()
    warp_options.append(elem)

    return ElementTree.tostring(vrt_root).decode()