本文整理汇总了Python中xml.etree.ElementTree.dump方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.dump方法的具体用法?Python ElementTree.dump怎么用?Python ElementTree.dump使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.dump方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def main(self, *, args):
try:
package_share_dir = get_package_share_directory(args.package_name)
except PackageNotFoundError:
return PACKAGE_NOT_FOUND
package_xml = os.path.join(package_share_dir, 'package.xml')
if not os.path.isfile(package_xml):
return PACKAGE_XML_NOT_FOUND
tree = ET.parse(package_xml)
if args.tag is None:
ET.dump(tree)
return 0
elements = tree.getroot().findall(args.tag)
if not elements:
return PACKAGE_XML_TAG_NOT_FOUND
for element in elements:
print(element.text)
示例2: closeReport
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def closeReport(self):
'''xmlReport.closeReport(): This method will write the xmlReport to disk.
@author: dkennel
'''
try:
if not self.closed:
ET.ElementTree(self.root).write(self.path)
self.closed = True
#if self.debug:
# print 'xmlReport.closeReport: dumping the ElementTree: '
# ET.dump(self.root)
except Exception as err:
if self.debug:
print('logdispatcher.xmlReport.closeReport: Error encountered processing xml')
print(err)
trace = traceback.format_exc()
print(trace)
示例3: closeReport
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def closeReport(self):
"""xmlReport.closeReport(): This method will write the xmlReport to disk.
@author: dkennel
"""
try:
if not self.closed:
f = open(self.path, 'w')
ET.ElementTree(self.root).write(f, encoding="unicode")
f.close()
self.closed = True
if self.debug:
print('xmlReport.closeReport: dumping the ElementTree: ')
ET.dump(self.root)
except Exception as err:
if self.debug:
print('logdispatcher.xmlReport.closeReport: Error encountered processing xml')
print(err)
trace = traceback.format_exc()
print(trace)
示例4: show_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def show_xml(document):
from xml.etree import ElementTree as XML
xml_document = XML.Element("results")
legs_xml = XML.SubElement(xml_document, 'legs')
for n, leg in enumerate(document['legs'], start=1):
leg_xml = XML.SubElement(legs_xml, 'leg', n=str(n))
leg_xml.text = leg
teams_xml = XML.SubElement(xml_document, 'teams')
for team in document['teams']:
team_xml = XML.SubElement(teams_xml, "team")
name_xml = XML.SubElement(team_xml, "name")
name_xml.text = team['name']
position_xml = XML.SubElement(team_xml, "position")
for n, position in enumerate(team['position'], start=1):
leg_xml = XML.SubElement(position_xml, "leg", n=str(n))
leg_xml.text = str(position)
pi = XML.ProcessingInstruction("xml", 'version="1.0"')
XML.dump(pi)
XML.dump(xml_document)
示例5: getcategory
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def getcategory(
basepath,
label,
):
classedict = {}
def initdic():
for clsname in classname_15:
wordname = datamap_15[clsname]
classedict[wordname] = []
initdic()
picklepath = os.path.join(basepath, 'pickle')
pickledir = os.path.join(picklepath, 'category-file.pickle')
if not os.path.isfile(pickledir):
labelpath = os.path.join(basepath, label)
filelist = GetFileFromThisRootDir(labelpath)
for fullname in filelist:
name = mybasename(fullname)
objects = parse_bod_poly(fullname)
for obj in objects:
#wordname = datamap[obj['name']]
wordname = obj['name']
if name not in classedict[wordname]:
classedict[wordname].append(name)
with open(pickledir, 'wb') as f:
pickle.dump(classedict, f, pickle.HIGHEST_PROTOCOL)
else:
with open(pickledir, 'rb') as f:
classedict = pickle.load(f)
return classedict
示例6: bod2pascal
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def bod2pascal(self):
pascalLabel_path = os.path.join(self.basepath, r'pascalLabel')
for basename in self.namelist:
objects = parse_bod_poly(os.path.join(self.labelpath, basename + '.txt'))
tree_root = ET.Element('annotation')
folder = ET.SubElement(tree_root, 'secondjpg')
filename = ET.SubElement(tree_root, basename)
size = ET.SubElement(tree_root, 'size')
width = ET.SubElement(size, 'width')
height = ET.SubElement(size, 'height')
## TODO: read imagesize from img or info
imgname = os.path.join(self.basepath, 'images', basename + '.jpg')
# img = cv2.imread(imgname)
width.text = str(1024)
height.text = str(1024)
for obj in objects:
object = ET.SubElement(tree_root, 'object')
ET.dump(tree_root)
name = ET.SubElement(object, 'name')
name.text = datamap[obj['name']]
difficult = ET.SubElement(object, 'difficult')
print('difficult:', obj['difficult'])
difficult.text = str(obj['difficult'])
print('type difficult.text:', type(difficult.text))
bndbox = ET.SubElement(object, 'bndbox')
xmin = ET.SubElement(bndbox, 'xmin')
xmax = ET.SubElement(bndbox, 'xmax')
ymin = ET.SubElement(bndbox, 'ymin')
ymax = ET.SubElement(bndbox, 'ymax')
poly = obj['poly']
bbox = dots4ToRec4(poly)
xmin.text = str(bbox[0])
ymin.text = str(bbox[1])
xmax.text = str(bbox[2])
ymax.text = str(bbox[3])
tree = ET.ElementTree(tree_root)
tree.write(os.path.join(pascalLabel_path, basename + '.xml'))
示例7: bug_xmltoolkitX1
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def bug_xmltoolkitX1():
"""
dump() doesn't flush the output buffer
>>> tree = ET.XML("<doc><table><tbody/></table></doc>")
>>> ET.dump(tree); sys.stdout.write("tail")
<doc><table><tbody /></table></doc>
tail
"""
示例8: assert_xml_equals
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def assert_xml_equals(x1, x2):
print("--------X1--------")
ET.dump(x1)
print("--------X2--------")
ET.dump(x2)
assert x1.tag == x2.tag
assert (x1.text or "").strip() == (x2.text or "").strip()
# assert x1.tail == x2.tail # Swagger does not change tail
assert x1.attrib == x2.attrib
assert len(x1) == len(x2)
for c1, c2 in zip(x1, x2):
assert_xml_equals(c1, c2)
示例9: from_smdx
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
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
示例10: dump_etree
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def dump_etree(self):
"""
Dump etree to console for debugging
Returns:
"""
self.logger.info('Dumping XML etree to console')
Et.dump(self.etree)
示例11: writeToExternalFile
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def writeToExternalFile( self, filename, metadata ):
tree = self.convertMetadataToXML( self, metadata )
#ET.dump(tree)
tree.write(filename, encoding='utf-8')
示例12: bod2pascal
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def bod2pascal(self):
pascalLabel_path = os.path.join(self.basepath, r'pascalLabel')
#pascalLabel_path = os.pardir.join(self.basepath, r'')
print('go in name list')
for basename in self.namelist:
print('basename:', basename)
#objects = parse_bod_poly(os.path.join(self.labelpath, basename + '.txt'))
objects = parse_bod_poly(os.path.join(self.wordlabelpath, basename + '.txt'))
tree_root = ET.Element('annotation')
folder = ET.SubElement(tree_root, 'secondjpg')
filename = ET.SubElement(tree_root, basename)
size = ET.SubElement(tree_root, 'size')
width = ET.SubElement(size, 'width')
height = ET.SubElement(size, 'height')
## TODO: read imagesize from img or info
imgname = os.path.join(self.basepath, 'images', basename + '.jpg')
# img = cv2.imread(imgname)
## need change with different width, height
width.text = str(608)
height.text = str(608)
for obj in objects:
object = ET.SubElement(tree_root, 'object')
ET.dump(tree_root)
name = ET.SubElement(object, 'name')
#name.text = datamap[obj['name']]
name.text = obj['name']
difficult = ET.SubElement(object, 'difficult')
print('difficult:', obj['difficult'])
difficult.text = str(obj['difficult'])
print('type difficult.text:', type(difficult.text))
bndbox = ET.SubElement(object, 'bndbox')
xmin = ET.SubElement(bndbox, 'xmin')
xmax = ET.SubElement(bndbox, 'xmax')
ymin = ET.SubElement(bndbox, 'ymin')
ymax = ET.SubElement(bndbox, 'ymax')
poly = obj['poly']
bbox = dots4ToRec4(poly)
xmin.text = str(bbox[0])
ymin.text = str(bbox[1])
xmax.text = str(bbox[2])
ymax.text = str(bbox[3])
tree = ET.ElementTree(tree_root)
tree.write(os.path.join(pascalLabel_path, basename + '.xml'))
示例13: export_dataset_to_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def export_dataset_to_xml(fn, sentence_pairs, labels):
# export in format semeval 2014, incomplete though! just for loading with existing dataloaders for ATSC
sentences_el = ET.Element('sentences')
sentimap_reverse = {
'POS': 'positive',
'NEU': 'neutral',
'NEG': 'negative',
'CONF': 'conflict'
}
for ix, (sentence, aspectterm) in enumerate(sentence_pairs):
# print(sentence)
sentiment = labels[ix]
sentence_el = ET.SubElement(sentences_el, 'sentence')
sentence_el.set('id', str(ix))
text = ET.SubElement(sentence_el, 'text')
text.text = str(sentence).strip()
aspect_terms_el = ET.SubElement(sentence_el, 'aspectTerms')
aspect_term_el = ET.SubElement(aspect_terms_el, 'aspectTerm')
aspect_term_el.set('term', aspectterm)
aspect_term_el.set('polarity', sentimap_reverse[sentiment])
aspect_term_el.set('from', str('0'))
aspect_term_el.set('to', str('0'))
def indent(elem, level=0):
i = "\n" + level * " "
j = "\n" + (level - 1) * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
indent(sentences_el)
# mydata = ET.dump(sentences_el)
mydata = ET.tostring(sentences_el)
with open(fn, "wb") as f:
# f.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>')
f.write(mydata)
f.close()
示例14: compare_resources
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import dump [as 别名]
def compare_resources(module, res1, res2):
# we now have 2 nodes that we can compare, so lets dump them into files for comparring
n1_file_fd, n1_tmp_path = tempfile.mkstemp()
n2_file_fd, n2_tmp_path = tempfile.mkstemp()
n1_file = open(n1_tmp_path, 'w')
n2_file = open(n2_tmp_path, 'w')
# dump the XML resource definitions into temporary files
sys.stdout = n1_file
ET.dump(res1)
sys.stdout = n2_file
ET.dump(res2)
sys.stdout = sys.__stdout__
# close files
n1_file.close()
n2_file.close()
# normalize the files and store results in new files - this also removes some unimportant spaces and stuff
n3_file_fd, n3_tmp_path = tempfile.mkstemp()
n4_file_fd, n4_tmp_path = tempfile.mkstemp()
rc, out, err = module.run_command('xmllint --format --output ' + n3_tmp_path + ' ' + n1_tmp_path)
rc, out, err = module.run_command('xmllint --format --output ' + n4_tmp_path + ' ' + n2_tmp_path)
# add files that should be cleaned up
module.add_cleanup_file(n1_tmp_path)
module.add_cleanup_file(n2_tmp_path)
module.add_cleanup_file(n3_tmp_path)
module.add_cleanup_file(n4_tmp_path)
# now compare files
diff = ''
rc, out, err = module.run_command('diff ' + n3_tmp_path + ' ' + n4_tmp_path)
if rc != 0:
# if there was difference then show the diff
n3_file = open(n3_tmp_path, 'r+')
n4_file = open(n4_tmp_path, 'r+')
if to_native_support:
# produce diff only where we have to_native function which give sensible output
# without 'to_native' whole text is wrapped as single line and not diffed
# seems that to_native was added in ansible-2.2 (commit 57701d7)
diff = {
'before_header': '',
'before': to_native(b''.join(n3_file.readlines())),
'after_header': '',
'after': to_native(b''.join(n4_file.readlines())),
}
return rc, diff