本文整理汇总了Python中xml.etree.ElementTree方法的典型用法代码示例。如果您正苦于以下问题:Python etree.ElementTree方法的具体用法?Python etree.ElementTree怎么用?Python etree.ElementTree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree
的用法示例。
在下文中一共展示了etree.ElementTree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _ValueOrPlaceHolder
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例2: ToXMLElement
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例3: __init__
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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()}
示例4: elementtree_to_dict
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例5: select_objectives
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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):
示例6: __init__
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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)
示例7: __init__
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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)
示例8: __str__
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例9: toXMLElement
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例10: set_attribute_on_first_child
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
def set_attribute_on_first_child(docfrag, name, value, treeName):
"""naively sets an attribute on the first child of the document
fragment passed in"""
setter = {'ElementTree': lambda d: d[0].set,
'DOM': lambda d: d.firstChild.setAttribute}
setter['cElementTree'] = setter['ElementTree']
try:
setter.get(treeName, setter['DOM'])(docfrag)(name, value)
except AttributeError:
setter['ElementTree'](docfrag)(name, value)
示例11: get_etree
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
def get_etree():
global _etree
if _etree is not None:
return _etree
try:
from lxml import etree as _etree
except ImportError:
try:
from xml.etree import cElementTree as _etree
except ImportError:
try:
from xml.etree import ElementTree as _etree
except ImportError:
raise TypeError('lxml or etree not found')
return _etree
示例12: __element_text
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
def __element_text(self, element):
"""Return ElementTree text or None
:param xml.etree.ElementTree element: ElementTree to get text.
:return str|None: Element text
"""
if element is not None and len(element.text):
return element.text
return None
示例13: properties
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
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
示例14: diff_summary
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
def diff_summary(self, old, new, rel_path=None):
"""Provides a summarized output of a diff between two revisions
(file, change type, file type)
"""
full_url_or_path = self.__url_or_path
if rel_path is not None:
full_url_or_path += '/' + rel_path
arguments = [
'--old', '{0}@{1}'.format(full_url_or_path, old),
'--new', '{0}@{1}'.format(full_url_or_path, new),
'--summarize',
'--xml',
]
result = self.run_command(
'diff',
arguments,
do_combine=True)
root = xml.etree.ElementTree.fromstring(result)
diff = []
for element in root.findall('paths/path'):
diff.append({
'path': element.text,
'item': element.attrib['item'],
'kind': element.attrib['kind'],
})
return diff
示例15: __init__
# 需要导入模块: from xml import etree [as 别名]
# 或者: from xml.etree import ElementTree [as 别名]
def __init__(self, graph=None, encoding="utf-8", prettyprint=True,
version='1.1draft'):
try:
import xml.etree.ElementTree
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,
'xmlns:viz':self.NS_VIZ,
'xsi:schemaLocation':self.SCHEMALOCATION,
'version':self.VERSION})
# 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)