Python xml.etree.cElementTree.SubElement() Examples

The following are 30 code examples of xml.etree.cElementTree.SubElement(). 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.cElementTree , or try the search function .
Example #1
Source File: cifar_data_processing.py    From batch-shipyard with MIT License 6 votes vote down vote up
def saveMean(fname, data):
    root = et.Element('opencv_storage')
    et.SubElement(root, 'Channel').text = '3'
    et.SubElement(root, 'Row').text = str(IMGSIZE)
    et.SubElement(root, 'Col').text = str(IMGSIZE)
    meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix')
    et.SubElement(meanImg, 'rows').text = '1'
    et.SubElement(meanImg, 'cols').text = str(IMGSIZE * IMGSIZE * 3)
    et.SubElement(meanImg, 'dt').text = 'f'
    et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (IMGSIZE * IMGSIZE * 3))])

    tree = et.ElementTree(root)
    tree.write(fname)
    x = xml.dom.minidom.parse(fname)
    with open(fname, 'w') as f:
        f.write(x.toprettyxml(indent = '  ')) 
Example #2
Source File: cifar_prepare.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def saveMean(fname, data):
    root = et.Element('opencv_storage')
    et.SubElement(root, 'Channel').text = '3'
    et.SubElement(root, 'Row').text = str(imgSize)
    et.SubElement(root, 'Col').text = str(imgSize)
    meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix')
    et.SubElement(meanImg, 'rows').text = '1'
    et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3)
    et.SubElement(meanImg, 'dt').text = 'f'
    et.SubElement(meanImg, 'data').text = ' '.join(
        ['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))]
    )

    tree = et.ElementTree(root)
    tree.write(fname)
    x = xml.dom.minidom.parse(fname)
    with open(fname, 'w') as f:
        f.write(x.toprettyxml(indent='  ')) 
Example #3
Source File: printers.py    From py-lua-parser with MIT License 6 votes vote down vote up
def visit(self, node):
        xml_node = ElementTree.Element(node.display_name)

        # attributes
        for attr, attrValue in node.__dict__.items():
            if not attr.startswith('_') and attrValue is not None:
                xml_attr = ElementTree.SubElement(xml_node, attr)
                child_node = self.visit(attrValue)
                if type(child_node) is str:
                    xml_attr.text = child_node
                elif type(child_node) is list:
                    xml_attr.extend(child_node)
                else:
                    xml_attr.append(child_node)

        return xml_node 
Example #4
Source File: 2_data_to_pascal_xml.py    From face-detection-ssd-mobilenet with Apache License 2.0 6 votes vote down vote up
def newXMLPASCALfile(imageheight, imagewidth, path, basename):
    # print(filename)
    annotation = ET.Element("annotation", verified="yes")
    ET.SubElement(annotation, "folder").text = "images"
    ET.SubElement(annotation, "filename").text = basename
    ET.SubElement(annotation, "path").text = path

    source = ET.SubElement(annotation, "source")
    ET.SubElement(source, "database").text = "test"

    size = ET.SubElement(annotation, "size")
    ET.SubElement(size, "width").text = str(imagewidth)
    ET.SubElement(size, "height").text = str(imageheight)
    ET.SubElement(size, "depth").text = "3"

    ET.SubElement(annotation, "segmented").text = "0"

    tree = ET.ElementTree(annotation)
    # tree.write("filename.xml")
    return tree 
Example #5
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def check_one_source(self, flink, si):
        package = si.get('package')

        # If the package is an internal one (e.g _product)
        if package.startswith('_'):
            return None

        # Ignore packages with an origing (i.e. with an origin
        # different from the current project)
        if si.find('originproject') != None:
            return None

        if package in ['rpmlint-mini-AGGR']:
            return package  # we should not freeze aggregates
        ET.SubElement(flink, 'package', {'name': package, 'srcmd5': si.get('srcmd5'), 'vrev': si.get('vrev')})
        return package 
Example #6
Source File: biarchtool.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def add_explicit_disable(self, wipebinaries=False):

        self._init_biarch_packages()

        resulturl = self.makeurl(['source', self.project])
        result = ET.fromstring(self.cached_GET(resulturl))

        for pkg in self.packages:

            changed = False

            logger.debug("processing %s", pkg)
            if not pkg in self.package_metas:
                logger.error("%s not found", pkg)
                continue
            pkgmeta = self.package_metas[pkg]

            build = pkgmeta.findall("./build")
            if not build:
                logger.debug('disable %s for %s', pkg, self.arch)
                bn = pkgmeta.find('build')
                if bn is None:
                    bn = ET.SubElement(pkgmeta, 'build')
                ET.SubElement(bn, 'disable', { 'arch': self.arch })
                changed = True

            if changed:
                try:
                    pkgmetaurl = self.makeurl(['source', self.project, pkg, '_meta'])
                    self.http_PUT(pkgmetaurl, data=ET.tostring(pkgmeta))
                    if self.caching:
                        self._invalidate__cached_GET(pkgmetaurl)
                    if wipebinaries:
                        self.http_POST(self.makeurl(['build', self.project], {
                            'cmd': 'wipe',
                            'arch': self.arch,
                            'package': pkg }))
                except HTTPError as e:
                    logger.error('failed to update %s: %s', pkg, e) 
Example #7
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def check_one_source(self, flink, si):
        package = si.get('package')

        # If the package is an internal one (e.g _product)
        if package.startswith('_'):
            return None

        # Ignore packages with an origing (i.e. with an origin
        # different from the current project)
        if si.find('originproject') != None:
            return None

        if package in ['rpmlint-mini-AGGR']:
            return package  # we should not freeze aggregates
        ET.SubElement(flink, 'package', {'name': package, 'srcmd5': si.get('srcmd5'), 'vrev': si.get('vrev')})
        return package 
Example #8
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def create_bootstrap_aggregate_file(self):
        url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_aggregate'])

        root = ET.Element('aggregatelist')
        a = ET.SubElement(root, 'aggregate',
                          {'project': '{}:0-Bootstrap'.format(self.api.crings)})

        for package in self.bootstrap_packages():
            p = ET.SubElement(a, 'package')
            p.text = package

        ET.SubElement(a, 'repository', {'target': 'bootstrap_copy', 'source': 'standard'})
        ET.SubElement(a, 'repository', {'target': 'standard', 'source': 'nothing'})
        ET.SubElement(a, 'repository', {'target': 'images', 'source': 'nothing'})

        self.api.retried_PUT(url, ET.tostring(root)) 
Example #9
Source File: GXXmlWriter.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def writeElementString(self, name, value, defaultValue=None):
        if isinstance(value, (GXIntEnum, GXIntFlag)):
            raise ValueError("Datatype is enum.")

        if not(value and self.skipDefaults) or value != defaultValue:
            if value is None:
                ET.SubElement(self.getTarget(), name)
            elif isinstance(value, str):
                ET.SubElement(self.getTarget(), name).text = value
            elif isinstance(value, GXDateTime):
                ET.SubElement(self.getTarget(), name).text = value.toFormatMeterString("%m/%d/%Y %H:%M:%S")
            elif isinstance(value, bool):
                if value:
                    ET.SubElement(self.getTarget(), name).text = "1"
                else:
                    ET.SubElement(self.getTarget(), name).text = "0"
            elif isinstance(value, int):
                ET.SubElement(self.getTarget(), name).text = str(value)
            elif isinstance(value, (bytearray, bytes)):
                ET.SubElement(self.getTarget(), name).text = GXByteBuffer.hex(value)
            elif isinstance(value, (float)):
                ET.SubElement(self.getTarget(), name).text = str(value).replace(",", ".") 
Example #10
Source File: __init__.py    From keras2pmml with MIT License 6 votes vote down vote up
def _generate_data_dictionary(root, feature_names, target_name, target_values):
    data_dict = ET.SubElement(root, 'DataDictionary')
    data_field = ET.SubElement(data_dict, 'DataField')
    data_field.set('name', target_name)
    data_field.set('dataType', 'string')
    data_field.set('optype', 'categorical')
    print('[x] Generating Data Dictionary:')
    for t in target_values:
        value = ET.SubElement(data_field, 'Value')
        value.set('value', t)
    for f in feature_names:
        data_field = ET.SubElement(data_dict, 'DataField')
        data_field.set('name', f)
        data_field.set('dataType', 'double')
        data_field.set('optype', 'continuous')
        print('\t[-] {}...OK!'.format(f))
    return data_dict 
Example #11
Source File: utils.py    From script.tvguide.fullscreen with GNU General Public License v2.0 5 votes vote down vote up
def generate_settings_file(target_path):
    source_path = xbmc.translatePath(
        os.path.join(ADDON.getAddonInfo('path'), 'resources', 'settings.xml'))
    root_target = ceT.Element("settings")
    tree_source = eT.parse(source_path)
    root_source = tree_source.getroot()
    for item in root_source.findall('category'):
        for setting in item.findall('setting'):
            if 'id' in setting.attrib:
                value = ''
                if 'default' in setting.attrib:
                    value = setting.attrib['default']
                ceT.SubElement(root_target, 'setting', id=setting.attrib['id'], value=value)
    tree_target = ceT.ElementTree(root_target)
    f = open(target_path, 'w')
    tree_target.write(f)
    f.close() 
Example #12
Source File: argument.py    From splunk-ref-pas-code with Apache License 2.0 5 votes vote down vote up
def add_to_document(self, parent):
        """Adds an ``Argument`` object to this ElementTree document.

        Adds an <arg> subelement to the parent element, typically <args>
        and sets up its subelements with their respective text.

        :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement
        :returns: An ``ET.Element`` object representing this argument.
        """
        arg = ET.SubElement(parent, "arg")
        arg.set("name", self.name)

        if self.description is not None:
            ET.SubElement(arg, "description").text = self.description

        if self.validation is not None:
            ET.SubElement(arg, "validation").text = self.validation

        # add all other subelements to this Argument, represented by (tag, text)
        subelements = [
            ("data_type", self.data_type),
            ("required_on_edit", self.required_on_edit),
            ("required_on_create", self.required_on_create)
        ]

        for name, value in subelements:
            ET.SubElement(arg, name).text = str(value).lower()

        return arg 
Example #13
Source File: event.py    From splunk-ref-pas-code with Apache License 2.0 5 votes vote down vote up
def write_to(self, stream):
        """Write an XML representation of self, an ``Event`` object, to the given stream.

        The ``Event`` object will only be written if its data field is defined,
        otherwise a ``ValueError`` is raised.

        :param stream: stream to write XML to.
        """
        if self.data is None:
            raise ValueError("Events must have at least the data field set to be written to XML.")

        event = ET.Element("event")
        if self.stanza is not None:
            event.set("stanza", self.stanza)
        event.set("unbroken", str(int(self.unbroken)))

        # if a time isn't set, let Splunk guess by not creating a <time> element
        if self.time is not None:
            ET.SubElement(event, "time").text = str(self.time)

        # add all other subelements to this Event, represented by (tag, text)
        subelements = [
            ("source", self.source),
            ("sourcetype", self.sourceType),
            ("index", self.index),
            ("host", self.host),
            ("data", self.data)
        ]
        for node, value in subelements:
            if value is not None:
                ET.SubElement(event, node).text = value

        if self.done is not None:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush() 
Example #14
Source File: argument.py    From SplunkForPCAP with MIT License 5 votes vote down vote up
def add_to_document(self, parent):
        """Adds an ``Argument`` object to this ElementTree document.

        Adds an <arg> subelement to the parent element, typically <args>
        and sets up its subelements with their respective text.

        :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement
        :returns: An ``ET.Element`` object representing this argument.
        """
        arg = ET.SubElement(parent, "arg")
        arg.set("name", self.name)

        if self.title is not None:
            ET.SubElement(arg, "title").text = self.title

        if self.description is not None:
            ET.SubElement(arg, "description").text = self.description

        if self.validation is not None:
            ET.SubElement(arg, "validation").text = self.validation

        # add all other subelements to this Argument, represented by (tag, text)
        subelements = [
            ("data_type", self.data_type),
            ("required_on_edit", self.required_on_edit),
            ("required_on_create", self.required_on_create)
        ]

        for name, value in subelements:
            ET.SubElement(arg, name).text = str(value).lower()

        return arg 
Example #15
Source File: 2_data_to_pascal_xml.py    From face-detection-ssd-mobilenet with Apache License 2.0 5 votes vote down vote up
def appendXMLPASCAL(curr_et_object,x1, y1, w, h, filename):
    et_object = ET.SubElement(curr_et_object.getroot(), "object")
    ET.SubElement(et_object, "name").text = "face"
    ET.SubElement(et_object, "pose").text = "Unspecified"
    ET.SubElement(et_object, "truncated").text = "0"
    ET.SubElement(et_object, "difficult").text = "0"
    bndbox = ET.SubElement(et_object, "bndbox")
    ET.SubElement(bndbox, "xmin").text = str(x1)
    ET.SubElement(bndbox, "ymin").text = str(y1)
    ET.SubElement(bndbox, "xmax").text = str(x1+w)
    ET.SubElement(bndbox, "ymax").text = str(y1+h)
    filename = filename.strip().replace(".jpg",".xml")
    curr_et_object.write(filename)
    return curr_et_object 
Example #16
Source File: tei_reden.py    From SEM with MIT License 5 votes vote down vote up
def add_tail(node, tail):
    parts = tail.split(u"\n")
    node.tail = parts[0]
    for i in range(1, len(parts)):
        br = ET.SubElement(node,"lb")
        br.tail = u"\n" + parts[1] 
Example #17
Source File: tei_np.py    From SEM with MIT License 5 votes vote down vote up
def add_text(node, text):
    parts = text.split(u"\n")
    node.text = parts[0]
    for i in range(1, len(parts)):
        br = ET.SubElement(node,"lb")
        br.tail = u"\n" + parts[1] 
Example #18
Source File: __init__.py    From keras2pmml with MIT License 5 votes vote down vote up
def _generate_header(root, kwargs):
    description = kwargs.get('description', None)
    copyright = kwargs.get('copyright', None)
    header = ET.SubElement(root, 'Header')
    if copyright:
        header.set('copyright', copyright)
    if description:
        header.set('description', description)
    timestamp = ET.SubElement(header, 'Timestamp')
    timestamp.text = str(datetime.now())
    return header 
Example #19
Source File: tei_reden.py    From SEM with MIT License 5 votes vote down vote up
def add_text(node, text):
    parts = text.split(u"\n")
    node.text = parts[0]
    for i in range(1, len(parts)):
        br = ET.SubElement(node,"lb")
        br.tail = u"\n" + parts[1] 
Example #20
Source File: printers.py    From py-lua-parser with MIT License 5 votes vote down vote up
def get_xml_string(self, tree):
        xml = self.visit(tree)

        ast = ElementTree.Element("ast")
        doc = ElementTree.SubElement(ast, "doc")
        doc.append(xml)

        return minidom.parseString(ElementTree.tostring(doc)).toprettyxml(indent="   ") 
Example #21
Source File: fcc_submitter.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def check_one_source(self, flink, si, pkglist, pkglist_prever):
        """
        Insert package information to the temporary frozenlinks.
        Return package name if the package can not fit the condition
        add to the frozenlinks, can be the ignored package.
        """
        package = si.get('package')
        logging.debug("Processing %s" % (package))

        # If the package is an internal one (e.g _product)
        if package.startswith('_') or package.startswith('Test-DVD') or package.startswith('000'):
            return None

        # filter out multibuild package
        for originpackage in si.findall('originpackage'):
            if ':' in package and package.split(':')[0] == originpackage.text:
                return package

        for linked in si.findall('linked'):
            if linked.get('project') == self.factory:
                if linked.get('package') in pkglist or linked.get('package') in pkglist_prever:
                    return package
                url = makeurl(self.apiurl, ['source', self.factory, package], {'view': 'info', 'nofilename': '1'})
                # print(package, linked.get('package'), linked.get('project'))
                f = http_GET(url)
                proot = ET.parse(f).getroot()
                lsrcmd5 = proot.get('lsrcmd5')
                if lsrcmd5 is None:
                    raise Exception("{}/{} is not a link but we expected one".format(self.factory, package))
                ET.SubElement(flink, 'package', {'name': package, 'srcmd5': lsrcmd5, 'vrev': si.get('vrev')})
                return None

        if package in pkglist or package in pkglist_prever:
            return package

        if package in ['rpmlint-mini-AGGR']:
            # we should not freeze aggregates
            return None

        ET.SubElement(flink, 'package', {'name': package, 'srcmd5': si.get('srcmd5'), 'vrev': si.get('vrev')})
        return None 
Example #22
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def freeze_prjlinks(self):
        sources = {}
        flink = ET.Element('frozenlinks')

        for lprj in self.projectlinks:
            fl = ET.SubElement(flink, 'frozenlink', {'project': lprj})
            sources = self.receive_sources(lprj, sources, fl)

        url = self.api.makeurl(['source', self.prj, '_project', '_frozenlinks'], {'meta': '1'})
        self.api.retried_PUT(url, ET.tostring(flink)) 
Example #23
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def create_bootstrap_aggregate_meta(self):
        url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_meta'])

        root = ET.Element('package', {'project': self.prj, 'name': 'bootstrap-copy'})
        ET.SubElement(root, 'title')
        ET.SubElement(root, 'description')
        f = ET.SubElement(root, 'build')
        # this one is to toggle
        ET.SubElement(f, 'disable', {'repository': 'bootstrap_copy'})
        # this one is the global toggle
        ET.SubElement(f, 'disable')

        self.api.retried_PUT(url, ET.tostring(root)) 
Example #24
Source File: GXDLMSObjectCollection.py    From Gurux.DLMS.Python with GNU General Public License v2.0 5 votes vote down vote up
def save(self, name, settings=None):
        writer = GXXmlWriter()
        objects = ET.Element("Objects")
        for it in self:
            node = ET.SubElement(objects, "GXDLMS" + GXDLMSConverter.objectTypeToString(it.objectType))
            if it.shortName != 0:
                ET.SubElement(node, "SN").text = str(it.shortName)
            ET.SubElement(node, "LN").text = it.logicalName
            if it.version != 0:
                ET.SubElement(node, "Version").text = str(it.version)
            if it.description:
                ET.SubElement(node, "Description").text = it.description
            if not settings or settings.values:
                writer.objects = []
                writer.objects.append(node)
                it.save(writer)
        str_ = minidom.parseString(ET.tostring(objects, encoding='utf-8', method='xml')).toprettyxml(indent="  ")
        with open(name, "w") as f:
            f.write(str_) 
Example #25
Source File: core.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def attribute_value_save(apiurl, project, name, value, namespace='OSRT', package=None):
    root = ET.Element('attributes')

    attribute = ET.SubElement(root, 'attribute')
    attribute.set('namespace', namespace)
    attribute.set('name', name)

    ET.SubElement(attribute, 'value').text = value

    # The OBS API of attributes is super strange, POST to update.
    url = makeurl(apiurl, list(filter(None, ['source', project, package, '_attribute'])))
    http_POST(url, data=ET.tostring(root)) 
Example #26
Source File: __init__.py    From keras2pmml with MIT License 5 votes vote down vote up
def _generate_neural_network(root, estimator, transformer, feature_names, target_name, target_values, model_name=None):
    neural_network = ET.SubElement(root, 'NeuralNetwork')
    neural_network.set('functionName', 'classification')
    neural_network.set('activationFunction', 'logistic') # default, will be overriden later
    neural_network.set('normalizationMethod', 'none') # default, will be overriden later

    if model_name:
        neural_network.set('modelName', model_name)

    _generate_mining_schema(neural_network, feature_names, target_name)
    _generate_output(neural_network, target_values)
    _generate_neural_inputs(neural_network, transformer, feature_names)
    _generate_neural_layers(neural_network, estimator)
    _generate_neural_outputs(neural_network, estimator, target_name, target_values)
    return neural_network 
Example #27
Source File: __init__.py    From keras2pmml with MIT License 5 votes vote down vote up
def _generate_mining_schema(neural_network, feature_names, target_name):
    mining_schema = ET.SubElement(neural_network, 'MiningSchema')
    mining_field = ET.SubElement(mining_schema, 'MiningField')
    mining_field.set('name', target_name)
    mining_field.set('usageType', 'target')
    for f in feature_names:
        mining_field = ET.SubElement(mining_schema, 'MiningField')
        mining_field.set('name', f)
        mining_field.set('usageType', 'active')
    return mining_schema 
Example #28
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def freeze_prjlinks(self):
        sources = {}
        flink = ET.Element('frozenlinks')

        for lprj in self.projectlinks:
            fl = ET.SubElement(flink, 'frozenlink', {'project': lprj})
            sources = self.receive_sources(lprj, sources, fl)

        url = self.api.makeurl(['source', self.prj, '_project', '_frozenlinks'], {'meta': '1'})
        self.api.retried_PUT(url, ET.tostring(flink)) 
Example #29
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def create_bootstrap_aggregate_meta(self):
        url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_meta'])

        root = ET.Element('package', {'project': self.prj, 'name': 'bootstrap-copy'})
        ET.SubElement(root, 'title')
        ET.SubElement(root, 'description')
        f = ET.SubElement(root, 'build')
        # this one is to toggle
        ET.SubElement(f, 'disable', {'repository': 'bootstrap_copy'})
        # this one is the global toggle
        ET.SubElement(f, 'disable')

        self.api.retried_PUT(url, ET.tostring(root)) 
Example #30
Source File: scheme.py    From SplunkForPCAP with MIT License 5 votes vote down vote up
def to_xml(self):
        """Creates an ``ET.Element`` representing self, then returns it.

        :returns root, an ``ET.Element`` representing this scheme.
        """
        root = ET.Element("scheme")

        ET.SubElement(root, "title").text = self.title

        # add a description subelement if it's defined
        if self.description is not None:
            ET.SubElement(root, "description").text = self.description

        # add all other subelements to this Scheme, represented by (tag, text)
        subelements = [
            ("use_external_validation", self.use_external_validation),
            ("use_single_instance", self.use_single_instance),
            ("streaming_mode", self.streaming_mode)
        ]
        for name, value in subelements:
            ET.SubElement(root, name).text = str(value).lower()

        endpoint = ET.SubElement(root, "endpoint")

        args = ET.SubElement(endpoint, "args")

        # add arguments as subelements to the <args> element
        for arg in self.arguments:
            arg.add_to_document(args)

        return root