Python xml.etree.ElementTree.dump() Examples

The following are 18 code examples of xml.etree.ElementTree.dump(). 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: logdispatcher_mock.py    From stonix with GNU General Public License v2.0 7 votes vote down vote up
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) 
Example #2
Source File: ch09_r06.py    From Modern-Python-Cookbook with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: logdispatcher.py    From stonix with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #4
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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

    """ 
Example #5
Source File: comicinfoxml.py    From ComicStreamer with Apache License 2.0 5 votes vote down vote up
def writeToExternalFile( self, filename, metadata ):
		
		tree = self.convertMetadataToXML( self, metadata )
		#ET.dump(tree)		
		tree.write(filename, encoding='utf-8') 
Example #6
Source File: comet.py    From ComicStreamer with Apache License 2.0 5 votes vote down vote up
def writeToExternalFile( self, filename, metadata ):
		
		tree = self.convertMetadataToXML( self, metadata )
		#ET.dump(tree)		
		tree.write(filename, encoding='utf-8') 
Example #7
Source File: xmlexporter.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def dump_etree(self):
        """
        Dump etree to console for debugging
        Returns:
        """
        self.logger.info('Dumping XML etree to console')
        Et.dump(self.etree) 
Example #8
Source File: utils.py    From DOTA_models with Apache License 2.0 5 votes vote down vote up
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 
Example #9
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 #10
Source File: test_xml_serialization.py    From msrest-for-python with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
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

    """ 
Example #12
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
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

    """ 
Example #13
Source File: xml.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source File: utils.py    From AerialDetection with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: utils.py    From DOTA_models with Apache License 2.0 5 votes vote down vote up
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')) 
Example #16
Source File: prepare_semeval_datasets.py    From domain-adapted-atsc with MIT License 4 votes vote down vote up
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() 
Example #17
Source File: utils.py    From AerialDetection with Apache License 2.0 4 votes vote down vote up
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')) 
Example #18
Source File: pcs_resource.py    From esdc-ce with Apache License 2.0 4 votes vote down vote up
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