Python xml.etree.ElementTree() Examples

The following are 30 code examples of xml.etree.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 xml.etree , or try the search function .
Example #1
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ToXMLElement(self):
    """Convert object to its ElementTree XML representation.

    Returns:
      An ElementTree Element.
    """
    topic_element = xml.etree.ElementTree.Element('topic')
    topic_element.set('id', self.topic_id)

    topic_info = xml.etree.ElementTree.Element('info')
    topic_name = xml.etree.ElementTree.Element('name')

    topic_name.append(
        _ValueOrPlaceHolder(
            self.topic_name,
            'NAME for topic: %s' % self.topic_id))
    topic_info.append(topic_name)
    topic_element.append(topic_info)

    for child_topic in self.children:
      topic_element.append(child_topic.ToXMLElement())

    return topic_element 
Example #2
Source File: graphml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, graph=None, encoding="utf-8", prettyprint=True,
                 infer_numeric_types=False):
        try:
            import xml.etree.ElementTree
        except ImportError:
            msg = 'GraphML writer requires xml.elementtree.ElementTree'
            raise ImportError(msg)
        self.myElement = Element

        self.infer_numeric_types = infer_numeric_types
        self.prettyprint = prettyprint
        self.encoding = encoding
        self.xml = self.myElement("graphml",
                                  {'xmlns': self.NS_GRAPHML,
                                   'xmlns:xsi': self.NS_XSI,
                                   'xsi:schemaLocation': self.SCHEMALOCATION})
        self.keys = {}
        self.attributes = defaultdict(list)
        self.attribute_types = defaultdict(set)

        if graph is not None:
            self.add_graph_element(graph) 
Example #3
Source File: graphml.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def __init__(self, graph=None, encoding="utf-8", prettyprint=True,
                 infer_numeric_types=False):
        try:
            import xml.etree.ElementTree
        except ImportError:
            msg = 'GraphML writer requires xml.elementtree.ElementTree'
            raise ImportError(msg)
        self.myElement = Element

        self.infer_numeric_types = infer_numeric_types
        self.prettyprint = prettyprint
        self.encoding = encoding
        self.xml = self.myElement("graphml",
                                  {'xmlns': self.NS_GRAPHML,
                                   'xmlns:xsi': self.NS_XSI,
                                   'xsi:schemaLocation': self.SCHEMALOCATION})
        self.keys = {}
        self.attributes = defaultdict(list)
        self.attribute_types = defaultdict(set)

        if graph is not None:
            self.add_graph_element(graph) 
Example #4
Source File: graphml.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, graph=None, encoding="utf-8",prettyprint=True):
        try:
            import xml.etree.ElementTree
        except ImportError:
             raise ImportError('GraphML writer requires '
                               'xml.elementtree.ElementTree')
        self.prettyprint=prettyprint
        self.encoding = encoding
        self.xml = Element("graphml",
                           {'xmlns':self.NS_GRAPHML,
                            'xmlns:xsi':self.NS_XSI,
                            'xsi:schemaLocation':self.SCHEMALOCATION}
                           )
        self.keys={}

        if graph is not None:
            self.add_graph_element(graph) 
Example #5
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ToXMLElement(self):
    """Convert object to its ElementTree XML representation.

    Returns:
      An ElementTree Element.
    """
    column_element = xml.etree.ElementTree.Element('column')
    column_element.set('id', self.column_id)
    column_element.set('type', self.data_type)

    if self.data_format:
      column_element.set('format', self.data_format)

    if self.constant_value:
      column_value_element = xml.etree.ElementTree.Element('value')
      column_value_element.text = self.constant_value
      column_element.append(column_value_element)

    return column_element 
Example #6
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ToXMLElement(self):
    """Convert object to its ElementTree XML representation.

    Returns:
      An ElementTree Element.
    """
    table_element = xml.etree.ElementTree.Element('table')
    table_element.set('id', self.table_id)

    for column in self.columns:
      table_element.append(column.ToXMLElement())

    table_data = xml.etree.ElementTree.Element('data')
    table_data_file = xml.etree.ElementTree.Element('file')
    table_data_file.set('encoding', 'utf-8')
    table_data_file.set('format', 'csv')
    table_data_file.text = self.file_name

    table_data.append(table_data_file)

    table_element.append(table_data)

    return table_element 
Example #7
Source File: World.py    From Wario-Land-3 with MIT License 6 votes vote down vote up
def __init__(self, engine):
		"""
		Stores and manages all world-related data, most important of all, the tiles.
		"""
		super(World, self).__init__(engine)
		self.grid_size = (1, 1)  # Size of grid in amount of tiles
		self.tile_size = (1, 1)  # Size of indiv. tiles
		self.tile_grid_layers = {}  # All tiles of all layers are stored in this list, see self.load_tmx()
		self.tmx_root = None  # Root used by ET to parse, see self.load_tmx()
		self.layer_names = ["background_color", "background", "sticky_background", "main"]
		self.tile_images = utilities.split_tiled_image(pygame.image.load("tileset_n1.png").convert(), (16, 16),
													   (225, 0, 225))
		# Create the tiles:
		self.tiles = {i: BaseTile((0, 0), engine, "deco", [img]) for img, i in zip(self.tile_images, range(len(self.tile_images)))}
		# Add an empty tile:
		self.tiles[-1] = EmptyTile()
		self.tile_by_types = {tile.get_material_group(): [] for tile in self.tiles.values()} 
Example #8
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _ValueOrPlaceHolder(value_string, description):
  """Embeds a string inside an XML <value>...</value> element.

  If the string is empty or None, an alternate string is used instead.

  Args:
    value_string: String to embed
    description: String to be used if the value string is empty or None.

  Returns:
    An ElementTree Element object.
  """
  value_element = xml.etree.ElementTree.Element('value')
  value_element.set('xml:lang', _VALUE_LANGUAGE)

  if value_string:
    value_element.text = value_string
  else:
    value_element.text = '** INSERT %s **' % description

  return value_element 
Example #9
Source File: mfrdb.py    From hwrt with MIT License 6 votes vote down vote up
def elementtree_to_dict(element):
    """Convert an xml ElementTree to a dictionary."""
    d = dict()
    if hasattr(element, "text") and element.text is not None:
        d["text"] = element.text

    d.update(list(element.items()))  # element's attributes

    for c in list(element):  # element's children
        if c.tag not in d:
            d[c.tag] = elementtree_to_dict(c)
        # an element with the same tag was already in the dict
        else:
            # if it's not a list already, convert it to a list and append
            if not isinstance(d[c.tag], list):
                d[c.tag] = [d[c.tag], elementtree_to_dict(c)]
            # append to the list
            else:
                d[c.tag].append(elementtree_to_dict(c))
    return d 
Example #10
Source File: create_objectives.py    From ray_scripts with GNU General Public License v3.0 6 votes vote down vote up
def select_objectives(folder=None, filename=None):
    """

    :param filename: os joined protocol name
    :param folder: folder from os to search within
    :return: tree: elementtree from xml file
    """
    if filename:
        tree = xml.etree.ElementTree.parse(filename)
    elif folder:
        # Search protocol list, parsing each XML file for protocols and goalsets
        logging.debug('Searching folder {} for protocols, goal sets'.format(folder))
        for f in os.listdir(folder):
            # This guy should prompt the user to find the appropriate file
            if f.endswith('.xml'):
                tree = xml.etree.ElementTree.parse(os.path.join(folder, f))
    return tree


# def add_goal(goal, plan, roi=None, targets=None, exam=None, case=None): 
Example #11
Source File: graphml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, path=None, string=None):
        if path is not None:
            self.xml = ElementTree(file=path)
        elif string is not None:
            self.xml = fromstring(string)
        else:
            raise ValueError("Must specify either 'path' or 'string' as kwarg")
        (keys, defaults) = self.find_graphml_keys(self.xml)
        for g in self.xml.findall("{%s}graph" % self.NS_GRAPHML):
            yield self.make_graph(g, keys, defaults) 
Example #12
Source File: gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, graph=None, encoding='utf-8', prettyprint=True,
                 version='1.2draft'):
        try:
            import xml.etree.ElementTree as ET
        except ImportError:
            raise ImportError('GEXF writer requires '
                              'xml.elementtree.ElementTree')
        self.prettyprint = prettyprint
        self.encoding = encoding
        self.set_version(version)
        self.xml = Element('gexf',
                           {'xmlns': self.NS_GEXF,
                            'xmlns:xsi': self.NS_XSI,
                            'xsi:schemaLocation': self.SCHEMALOCATION,
                            'version': self.VERSION})

        ET.register_namespace('viz', self.NS_VIZ)

        # counters for edge and attribute identifiers
        self.edge_id = itertools.count()
        self.attr_id = itertools.count()
        self.all_edge_ids = set()
        # default attributes are stored in dictionaries
        self.attr = {}
        self.attr['node'] = {}
        self.attr['edge'] = {}
        self.attr['node']['dynamic'] = {}
        self.attr['node']['static'] = {}
        self.attr['edge']['dynamic'] = {}
        self.attr['edge']['static'] = {}

        if graph is not None:
            self.add_graph(graph) 
Example #13
Source File: graphml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, node_type=str, edge_key_type=int):
        try:
            import xml.etree.ElementTree
        except ImportError:
            msg = 'GraphML reader requires xml.elementtree.ElementTree'
            raise ImportError(msg)
        self.node_type = node_type
        self.edge_key_type = edge_key_type
        self.multigraph = False  # assume multigraph and test for multiedges
        self.edge_ids = {}  # dict mapping (u,v) tuples to id edge attributes 
Example #14
Source File: gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, stream):
        self.xml = ElementTree(file=stream)
        g = self.xml.find('{%s}graph' % self.NS_GEXF)
        if g is not None:
            return self.make_graph(g)
        # try all the versions
        for version in self.versions:
            self.set_version(version)
            g = self.xml.find('{%s}graph' % self.NS_GEXF)
            if g is not None:
                return self.make_graph(g)
        raise nx.NetworkXError('No <graph> element in GEXF file.') 
Example #15
Source File: gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, node_type=None, version='1.2draft'):
        try:
            import xml.etree.ElementTree
        except ImportError:
            raise ImportError('GEXF reader requires '
                              'xml.elementtree.ElementTree.')
        self.node_type = node_type
        # assume simple graph and test for multigraph on read
        self.simple_graph = True
        self.set_version(version) 
Example #16
Source File: gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write(self, fh):
        # Serialize graph G in GEXF to the open fh
        if self.prettyprint:
            self.indent(self.xml)
        document = ElementTree(self.xml)
        document.write(fh, encoding=self.encoding, xml_declaration=True) 
Example #17
Source File: gexf.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, stream):
        self.xml = ElementTree(file=stream)
        g=self.xml.find("{%s}graph" % self.NS_GEXF)
        if g is not None:
            return self.make_graph(g)
        # try all the versions
        for version in self.versions:
            self.set_version(version)
            g=self.xml.find("{%s}graph" % self.NS_GEXF)
            if g is not None:
                return self.make_graph(g)
        raise nx.NetworkXError("No <graph> element in GEXF file") 
Example #18
Source File: graphml.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_module(module):
    from nose import SkipTest
    try:
        import xml.etree.ElementTree
    except:
        raise SkipTest("xml.etree.ElementTree not available")


# fixture for nose tests 
Example #19
Source File: util.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def isBlockLevel(tag):
    """Check if the tag is a block level HTML tag."""
    if isinstance(tag, str):
        return tag.lower().rstrip('/') in BLOCK_LEVEL_ELEMENTS
    # Some ElementTree tags are not strings, so return False.
    return False 
Example #20
Source File: gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self, graph=None, encoding='utf-8', prettyprint=True,
                 version='1.2draft'):
        try:
            import xml.etree.ElementTree as ET
        except ImportError:
            raise ImportError('GEXF writer requires '
                              'xml.elementtree.ElementTree')
        self.prettyprint = prettyprint
        self.encoding = encoding
        self.set_version(version)
        self.xml = Element('gexf',
                           {'xmlns': self.NS_GEXF,
                            'xmlns:xsi': self.NS_XSI,
                            'xsi:schemaLocation': self.SCHEMALOCATION,
                            'version': self.VERSION})

        ET.register_namespace('viz', self.NS_VIZ)

        # counters for edge and attribute identifiers
        self.edge_id = itertools.count()
        self.attr_id = itertools.count()
        # default attributes are stored in dictionaries
        self.attr = {}
        self.attr['node'] = {}
        self.attr['edge'] = {}
        self.attr['node']['dynamic'] = {}
        self.attr['node']['static'] = {}
        self.attr['edge']['dynamic'] = {}
        self.attr['edge']['static'] = {}

        if graph is not None:
            self.add_graph(graph) 
Example #21
Source File: gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def write(self, fh):
        # Serialize graph G in GEXF to the open fh
        if self.prettyprint:
            self.indent(self.xml)
        document = ElementTree(self.xml)
        document.write(fh, encoding=self.encoding, xml_declaration=True) 
Example #22
Source File: gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self, node_type=None, version='1.2draft'):
        try:
            import xml.etree.ElementTree
        except ImportError:
            raise ImportError('GEXF reader requires '
                              'xml.elementtree.ElementTree.')
        self.node_type = node_type
        # assume simple graph and test for multigraph on read
        self.simple_graph = True
        self.set_version(version) 
Example #23
Source File: gexf.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __call__(self, stream):
        self.xml = ElementTree(file=stream)
        g = self.xml.find('{%s}graph' % self.NS_GEXF)
        if g is not None:
            return self.make_graph(g)
        # try all the versions
        for version in self.versions:
            self.set_version(version)
            g = self.xml.find('{%s}graph' % self.NS_GEXF)
            if g is not None:
                return self.make_graph(g)
        raise nx.NetworkXError('No <graph> element in GEXF file.') 
Example #24
Source File: graphml.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self, node_type=str, edge_key_type=int):
        try:
            import xml.etree.ElementTree
        except ImportError:
            msg = 'GraphML reader requires xml.elementtree.ElementTree'
            raise ImportError(msg)
        self.node_type = node_type
        self.edge_key_type = edge_key_type
        self.multigraph = False  # assume multigraph and test for multiedges
        self.edge_ids = {}  # dict mapping (u,v) tuples to id edge attributes 
Example #25
Source File: graphml.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __call__(self, path=None, string=None):
        if path is not None:
            self.xml = ElementTree(file=path)
        elif string is not None:
            self.xml = fromstring(string)
        else:
            raise ValueError("Must specify either 'path' or 'string' as kwarg")
        (keys, defaults) = self.find_graphml_keys(self.xml)
        for g in self.xml.findall("{%s}graph" % self.NS_GRAPHML):
            yield self.make_graph(g, keys, defaults) 
Example #26
Source File: graphml.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setup_module(module):
    from nose import SkipTest
    try:
        import xml.etree.ElementTree
    except:
        raise SkipTest("xml.etree.ElementTree not available")


# fixture for nose tests 
Example #27
Source File: common.py    From PySvn with GNU General Public License v2.0 5 votes vote down vote up
def properties(self, rel_path=None):
        """ Return a dictionary with all svn-properties associated with a
            relative path.
        :param rel_path: relative path in the svn repo to query the
                         properties from
        :returns: a dictionary with the property name as key and the content
                  as value
        """

        full_url_or_path = self.__url_or_path
        if rel_path is not None:
            full_url_or_path += '/' + rel_path

        result = self.run_command(
            'proplist',
            ['--xml', full_url_or_path],
            do_combine=True)

        # query the proper list of this path
        root = xml.etree.ElementTree.fromstring(result)
        target_elem = root.find('target')
        property_names = [p.attrib["name"]
                          for p in target_elem.findall('property')]

        # now query the content of each propery
        property_dict = {}

        for property_name in property_names:
            result = self.run_command(
                'propget',
                ['--xml', property_name, full_url_or_path, ],
                do_combine=True)
            root = xml.etree.ElementTree.fromstring(result)
            target_elem = root.find('target')
            property_elem = target_elem.find('property')
            property_dict[property_name] = property_elem.text

        return property_dict 
Example #28
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
    """Make a 'pretty' version of the dataset XML, with two-space indents.

    TODO(yolken): Cache results for better performance.

    Returns:
      A string of the dataset XML
    """
    result = xml.dom.minidom.parseString(
        xml.etree.ElementTree.tostring(
            self.ToXMLElement(), encoding='utf-8')).toprettyxml(indent='  ')

    return result 
Example #29
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ToXMLElement(self):
    """Convert object to its ElementTree XML representation.

    Returns:
      An ElementTree Element.
    """
    import_element = xml.etree.ElementTree.Element('import')
    import_element.set('namespace', self.namespace_url)

    return import_element 
Example #30
Source File: dspl_model.py    From dspl with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toXMLElement(self):
    """Convert object to its ElementTree XML representation.

    Returns:
      An ElementTree Element.
    """
    property_element = xml.etree.ElementTree.Element('property')
    property_element.set('concept', self.concept_ref)

    if self.is_parent:
      property_element.set('isParent', 'true')

    return property_element