Python elementtree.ElementTree.Element() Examples

The following are 30 code examples of elementtree.ElementTree.Element(). 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 skip_subject_body(self, type, token, start, end, line):
        # for now, just hand control back to the pythondoc scanner,
        # and let it skip over the subject body while looking for the
        # next marker.
        return self.look_for_pythondoc(type, token, start, end, line)

##
# Parses a module.
# <p>
# This function creates a {@link #ModuleParser} instance, and uses it
# to parse the given file.  For details, see {@linkplain #ModuleParser
# the <b>ModuleParser</b> documentation}.
#
# @param file Name of the module source file, or a file object.
# @param prefix Optional name prefix.
# @keyparam docstring If true, look for markup in docstrings.
# @return An element tree containing the module description.
# @defreturn Element.
# @exception IOError If the file could not be found, or could not
#    be opened for reading. 
Example #2
Source File: device.py    From pysunspec with MIT License 6 votes vote down vote up
def to_pics(self, parent, single_repeating=True):
        """ Adds the model and all elements within the model to the parent
        element. If *single_repeating* is True, only the first repeating block
        is added to the document.

        Parameters:

            parent :
                Element Tree element on which to place the model element.

            single_repeating :
                Flag to indicate whether to include a single or all repeating
                blocks within the model in the PICS document.
        """

        attr = {pics.PICS_ATTR_ID: str(self.id), pics.PICS_ATTR_LEN: str(self.len)}

        if self.index != 1:
            attr[pics.PICS_ATTR_INDEX] = str(self.index)

        e = ET.SubElement(parent, pics.PICS_MODEL, attrib=attr)

        for block in self.blocks:
            if single_repeating == False or block.index <= 1:
                block.to_pics(e) 
Example #3
Source File: device.py    From pysunspec with MIT License 6 votes vote down vote up
def to_pics(self, parent):
        """Adds the point to the parent element.

        Parameters:

            parent :
                Element Tree element on which to place the point element.
        """

        attr = {pics.PICS_ATTR_ID: str(self.point_type.id)}

        if self.value is None:
            attr[pics.PICS_ATTR_IMPLEMENTED] = str(pics.PICS_IMPLEMENTED_FALSE)
        else:
            if self.point_type.access != suns.SUNS_ACCESS_R:
                access =  [key for key, value in pics.pics_access_types.items() if value == suns.SUNS_ACCESS_RW][0]
                attr[pics.PICS_ATTR_ACCESS] = str(access)

        e = ET.SubElement(parent, pics.PICS_POINT, attrib=attr)
        if self.value_base is not None:
            e.text = str(self.value_base).rstrip('\0') 
Example #4
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def getsummary(description):

    description = flatten(description)

    # extract the first sentence from the description
    m = re.search("(?s)(.+?\.)\s", description + " ")
    if m:
        return m.group(1)

    return description # sorry

##
# (Helper) Parses HTML descriptor text into an XHTML structure.
#
# @param parser Parser instance (provides a warning method).
# @param text Text fragment.
# @return An element tree containing XHTML data.
# @defreturn Element. 
Example #5
Source File: device.py    From pysunspec with MIT License 6 votes vote down vote up
def from_pics(self, element):
        """Sets the block contents based on an element tree model type element
        contained in a SunSpec PICS document.

        Parameters:

            element :
                Element Tree model element.
        """

        for p in element.findall('*'):
            if p.tag != pics.PICS_POINT:
                raise SunSpecError("Unexpected '{}' element in '{}' element".format(p.tag, element.tag))
            pid = p.attrib.get(pics.PICS_ATTR_ID)
            point = self.points.get(pid)
            if point is None:
                point = self.points_sf.get(pid)
            if point is not None:
                point.from_pics(p)

        # resolve scale factor values in points, must be done after all points in block are read
        for point in self.points_list:
            if point.sf_point is not None:
                point.value_sf = point.sf_point.value_base 
Example #6
Source File: device.py    From pysunspec with MIT License 6 votes vote down vote up
def to_pics(self, parent, single_repeating=True):
        """Adds the device and all elements within the device to the parent
        element. If *single_repeating* is True, only the first repeating block
        for each model is added to the document.

        Parameters:

            parent :
                Element Tree element on which to place the device element.

            single_repeating :
                Flag to indicate whether to include a single or all repeating
                blocks within each model in the PICS document.
        """

        attr = {pics.PICS_ATTR_VERSION: str(pics.PICS_VERSION)}

        e = ET.SubElement(parent, pics.PICS_DEVICE, attrib=attr)

        for model in self.models_list:
            model.to_pics(e, single_repeating=single_repeating) 
Example #7
Source File: data.py    From pysunspec with MIT License 6 votes vote down vote up
def to_xml_str(self, pretty_print=False):

        attr = {}

        if self.version:
            attr[SDX_SUNSPEC_DATA_VERSION] = self.version

        self.root = ET.Element(SDX_SUNSPEC_DATA, attrib=attr)
        for d in self.device_data:
            d.to_xml(self.root)

        if pretty_print:
            util.indent(self.root)

        out = ET.tostring(self.root)
        if sys.version_info > (3,):
            temp = ""
            for i in out:
                temp += chr(i)
            out = temp

        return out 
Example #8
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def getsummary(description):

    description = flatten(description)

    # extract the first sentence from the description
    m = re.search("(?s)(.+?\.)\s", description + " ")
    if m:
        return m.group(1)

    return description # sorry

##
# (Helper) Parses HTML descriptor text into an XHTML structure.
#
# @param parser Parser instance (provides a warning method).
# @param text Text fragment.
# @return An element tree containing XHTML data.
# @defreturn Element. 
Example #9
Source File: core.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _harvest_tree(self, tree, version=1):
    """Populates object members from the data in the tree Element."""
    qname, elements, attributes = self.__class__._get_rules(version)
    for element in tree:
      if elements and element.tag in elements:
        definition = elements[element.tag]
        # If this is a repeating element, make sure the member is set to a
        # list.
        if definition[2]:
          if getattr(self, definition[0]) is None:
            setattr(self, definition[0], [])
          getattr(self, definition[0]).append(_xml_element_from_tree(element,
              definition[1], version))
        else:
          setattr(self, definition[0], _xml_element_from_tree(element,
              definition[1], version))
      else:
        self._other_elements.append(_xml_element_from_tree(element, XmlElement,
                                                           version))
    for attrib, value in tree.attrib.items():
      if attributes and attrib in attributes:
        setattr(self, attributes[attrib], value)
      else:
        self._other_attributes[attrib] = value
    if tree.text:
      self.text = tree.text 
Example #10
Source File: bigtable.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_kid_et():
            """Kid template + cElementTree"""
            _table = cet.Element('table')
            for row in table:
                td = cet.SubElement(_table, 'tr')
                for c in row.values():
                    cet.SubElement(td, 'td').text=str(c)
            kid_tmpl2.table = _table
            kid_tmpl2.serialize(output='html') 
Example #11
Source File: __init__.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
    if attrib is None:
        attrib = {}
    tag, attrib = fix_ns(tag, attrib, nsdict)
    if WhichElementTree == 'lxml':
        el = etree.Element(tag, attrib, nsmap=nsmap)
    else:
        el = _ElementInterfaceWrapper(tag, attrib)
    return el 
Example #12
Source File: __init__.py    From blackmamba with MIT License 5 votes vote down vote up
def handle_basic_atts(self, node):
        if isinstance(node, nodes.Element) and node['ids']:
            self.pending_ids += node['ids'] 
Example #13
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def ToString(self):
    element_tree = self._TransferToElementTree(ElementTree.Element(''))
    return ElementTree.tostring(element_tree, encoding="UTF-8") 
Example #14
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _ToElementTree(self):
    """

    Note, this method is designed to be used only with classes that have a
    _tag and _namespace. It is placed in AtomBase for inheritance but should
    not be called on this class.

    """
    new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
                                               self.__class__._tag))
    self._AddMembersToElementTree(new_tree)
    return new_tree 
Example #15
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _ToElementTree(self):
    new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
                                               self.column))
    self._AddMembersToElementTree(new_tree)
    return new_tree 
Example #16
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _BecomeChildElement(self, tree):
    new_child = ElementTree.Element('')
    tree.append(new_child)
    new_child.tag = '{%s}%s' % (self.__class__._namespace, 
                                self.column)
    self._AddMembersToElementTree(new_child) 
Example #17
Source File: bigtable.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cet():
        """cElementTree"""
        _table = cet.Element('table')
        for row in table:
            tr = cet.SubElement(_table, 'tr')
            for c in row.values():
                cet.SubElement(tr, 'td').text=str(c)
        cet.tostring(_table) 
Example #18
Source File: bigtable.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_et():
        """ElementTree"""
        _table = et.Element('table')
        for row in table:
            tr = et.SubElement(_table, 'tr')
            for c in row.values():
                et.SubElement(tr, 'td').text=str(c)
        et.tostring(_table) 
Example #19
Source File: __init__.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _BecomeChildElement(self, tree):
    """

    Note: Only for use with classes that have a _tag and _namespace class
    member. It is in AtomBase so that it can be inherited but it should
    not be called on instances of AtomBase.

    """
    new_child = ElementTree.Element('')
    tree.append(new_child)
    new_child.tag = '{%s}%s' % (self.__class__._namespace,
                                self.__class__._tag)
    self._AddMembersToElementTree(new_child) 
Example #20
Source File: __init__.py    From blackmamba with MIT License 5 votes vote down vote up
def add_doc_title(self):
        text = self.settings.title
        if text:
            self.title = text
            if not self.found_doc_title:
                el = Element('text:p', attrib = {
                    'text:style-name': self.rststyle('title'),
                    })
                el.text = text
                self.body_text_element.insert(0, el)
        el = self.find_first_text_p(self.body_text_element)
        if el is not None:
            self.attach_page_style(el) 
Example #21
Source File: __init__.py    From blackmamba 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 #22
Source File: __init__.py    From blackmamba with MIT License 5 votes vote down vote up
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
    if attrib is None:
        attrib = {}
    tag, attrib = fix_ns(tag, attrib, nsdict)
    if WhichElementTree == 'lxml':
        el = etree.Element(tag, attrib, nsmap=nsmap)
    else:
        el = _ElementInterfaceWrapper(tag, attrib)
    return el 
Example #23
Source File: xmltopicdefnprovider.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exportTopicTreeSpecXml(moduleName=None, rootTopic=None, bak='bak', moduleDoc=None):
    """
    If rootTopic is None, then pub.getDefaultTopicTreeRoot() is assumed.
    """

    if rootTopic is None:
        from .. import pub
        rootTopic = pub.getDefaultTopicTreeRoot()
    elif py2and3.isstring(rootTopic):
        from .. import pub
        rootTopic = pub.getTopic(rootTopic)

    tree = ET.Element('topicdefntree')
    if moduleDoc:
        mod_desc = ET.SubElement(tree, 'description')
        mod_desc.text = ' '.join(moduleDoc.split())

    traverser = pub.TopicTreeTraverser(XmlVisitor(tree))
    traverser.traverse(rootTopic)

    indent(tree)

    if moduleName:

        filename = '%s.xml' % moduleName
        if bak:
            pub._backupIfExists(filename, bak)

        fulltree= ET.ElementTree(tree)
        fulltree.write(filename, "utf-8", True)

    return ET.tostring(tree) 
Example #24
Source File: xmltopicdefnprovider.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_elem(elem):
    """Assume an ETree.Element object or a string representation.
    Return the ETree.Element object"""
    if not ET.iselement(elem):
        try:
            elem = ET.fromstring(elem)
        except:
            py2and3.print_("Value Error", elem)
            raise ValueError("Cannot convert to element")
    return elem 
Example #25
Source File: device.py    From pysunspec with MIT License 5 votes vote down vote up
def from_smdx(self, element):
        """ Sets the block type attributes based on an element tree block type
        element contained in an SMDX model definition.

        Parameters:

            element :
                Element Tree block type element.
        """

        btype = element.attrib.get(smdx.SMDX_ATTR_TYPE, smdx.SMDX_ATTR_TYPE_FIXED)

        if btype != smdx.SMDX_ATTR_TYPE_FIXED and btype != smdx.SMDX_ATTR_TYPE_REPEATING:
            raise SunSpecError('Invalid block type')

        self.type = smdx.smdx_block_types.get(btype)
        self.len = element.attrib.get(smdx.SMDX_ATTR_LEN)
        if self.len is None:
            raise SunSpecError('Block len error')
        self.name = element.attrib.get(smdx.SMDX_ATTR_NAME)
        if self.name is None:
            self.name = self.type

        # process points
        for e in element.findall(smdx.SMDX_POINT):
            pt = PointType(block_type=self)
            pt.from_smdx(e)

            if self.points.get(pt.id) is not None:
                ET.dump(e)
                raise SunSpecError('Duplicate point definition: %s' % (pt.id))

            self.points_list.append(pt)
            self.points[pt.id] = pt 
Example #26
Source File: device.py    From pysunspec with MIT License 5 votes vote down vote up
def from_pics(self, element):
        """ Sets the model contents based on an element tree model type element
        contained in a SunSpec PICS document.

        Parameters:

            element :
                Element Tree model element.
        """

        # update index if present
        self.index = element.attrib.get(pics.PICS_ATTR_INDEX, self.index)

        for b in element.findall('*'):
            if b.tag != pics.PICS_BLOCK:
                raise SunSpecError("Unexpected '{}' element in '{}' element".format(b.tag, element.tag))
            block_type = pics.pics_block_types.get(b.attrib.get(pics.PICS_ATTR_TYPE, pics.PICS_TYPE_FIXED))
            if block_type is None:
                raise SunSpecError('Unknown block type')
            if block_type == suns.SUNS_BLOCK_FIXED:
                if len(self.blocks) > 0:
                    self.blocks[0].from_pics(b)
            elif block_type == suns.SUNS_BLOCK_REPEATING:
                block_index = b.attrib.get(pics.PICS_ATTR_INDEX)
                # if no index specified, apply to all repeating blocks
                if block_index is None:
                    if len(self.blocks) > 1:
                        for block in self.blocks[1:]:
                            block.from_pics(b)
                else:
                    block_index = int(block_index)
                    if len(self.blocks) < block_index:
                        raise SunSpecError('Block index out of range: %s' % (str(block_index)))
                    self.blocks[block_index].from_pics(b)
            else:
                raise SunSpecError('Internal block type error') 
Example #27
Source File: device.py    From pysunspec with MIT License 5 votes vote down vote up
def from_pics(self, element):
        """Sets the block contents based on an element tree model type element
        contained in a SunSpec PICS document.

        Parameters:

            element :
                Element Tree model element.
        """

        impl = True
        impl_attr = element.attrib.get(pics.PICS_ATTR_IMPLEMENTED)
        if impl_attr:
            if impl_attr == pics.PICS_IMPLEMENTED_FALSE:
                impl = False

        value = None
        if impl:
            if element.text:
                value = self.point_type.to_value(element.text)
                self.impl = self.point_type.is_impl(value)
        else:
            self.impl = False

        if self.impl and value is not None:
            self.value_base = value 
Example #28
Source File: mbmap.py    From pysunspec with MIT License 5 votes vote down vote up
def to_xml(self, parent=None, no_data=False):

        attr = {}
        attr[MBMAP_ADDR] = str(self.base_addr)
        attr[MBMAP_FUNC] =  func_name.get(self.func, MBMAP_FUNC_HOLDING)
        if self.ns is not None:
            attr[MBMAP_NS] = str(self.ns)
        if self.lid is not None:
            attr[MBMAP_LID] = str(self.lid)
        if self.mapid is not None:
            attr[MBMAP_MAPID] = str(self.mapid)
        if self.time is not None:
            attr[MBMAP_TIME] = str(self.time)

        if parent is None:
            element = ET.Element(MBMAP_ROOT, attrib=attr)
        else:
            element = ET.SubElement(parent, MBMAP_ROOT, attrib=attr)

        for regs in self.regs:
            e = ET.SubElement(element, MBMAP_REGS, attrib={MBMAP_REGS_OFFSET: str(regs.offset), MBMAP_REGS_LEN: str(regs.count)})

            if no_data is False:
                s = ''
                if sys.version_info > (3,):
                    # Iterating over python 3 bytes gives integers
                    for d in regs.data:
                        s += '%02x' % d
                else:
                    for d in regs.data:
                        s += '%02x' % ord(d)
                e.text = s

        return element 
Example #29
Source File: data.py    From pysunspec with MIT License 5 votes vote down vote up
def to_xml(self, parent=None):

        attr = {}

        if self.version:
            attr[SDX_SUNSPEC_DATA_VERSION] = self.version

        if parent is None:
            self.root = ET.Element(SDX_SUNSPEC_DATA, attrib=attr)
        else:
            self.root = ET.SubElement(parent, SDX_SUNSPEC_DATA, attrib=attr)

        for d in self.device_data:
            d.to_xml(self.root) 
Example #30
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 5 votes vote down vote up
def __init__(self, options=None):
        self.options = options or {}

    ##
    # Writes an element containing some text (plain or formatted).
    #
    # @param elem Element.
    # @param compact If true, try to minimize the amount of vertical
    #     padding.