Python xml.etree.cElementTree 模块,SubElement() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.cElementTree.SubElement()

项目:RedHat    作者:opencontrol    | 项目源码 | 文件源码
def xccdf_subelement(xccdftree, xccdf_element, yamlcontent, yaml_key, override=None, attrib=None):
    yaml_key = yaml_key_value(yamlcontent, yaml_key)

    if yaml_key:
        new_element = ET.SubElement(xccdftree, xccdf_element)
        if type(yaml_key) is dict:
            if 'id' in yaml_key.keys():
                new_element.set("id", yaml_key["id"])
            if "clause" in yaml_key.keys():
                new_element.set("clause", yaml_key["clause"])
            if "description" in yaml_key.keys():
                new_element.text = yaml_key["description"]
        else:
            if xccdf_element is not "oval":
                new_element.text = str(yaml_key)
        if yaml_key_value(yamlcontent, override) is not None:
            new_element.set("override", str(yaml_key_value(yamlcontent, override)).lower())
        if attrib is not None:
            if type(attrib) is dict:
                new_element = add_attrib_to_element(new_element, attrib, yamlcontent)
            else:
                new_element = add_attrib_to_element(new_element, attrib)

    return xccdftree
项目:RedHat    作者:opencontrol    | 项目源码 | 文件源码
def script_to_rule_mapping(self, xccdftree, filename, script_content):
        if filename.endswith(".yml"):
            system = "urn:xccdf:fix:script:ansible"
        elif filename.endswith(".sh"):
            system = "urn:xccdf:fix:script:sh"
        elif filename.endswith(".anaconda"):
            system = "urn:redhat:anaconda:pre"
        elif filename.endswith(".pp"):
            system = "urn:xccdf:fix:script:puppet"
        elif filename.endswith(".chef"):
            system = "urn:xccdf:fix:script:chef"
        elif filename.endswith(".rb"):
            system = "urn:xccdf:fix:script:ruby"
        elif filename.endswith(".py"):
            system = "urn:xccdf:fix:script:python"

        filename = os.path.basename(filename).split(".")[0]
        for rule in xccdftree.iter("Rule"):
            if rule.attrib["id"] == filename:
                script = ET.SubElement(rule, "fix", system=system)
                script.text = script_content

        return xccdftree
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
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='  '))
项目:k8scntkSamples    作者:weehyong    | 项目源码 | 文件源码
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 = '  '))
项目:k8scntkSamples    作者:weehyong    | 项目源码 | 文件源码
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 = '  '))
项目:k8scntkSamples    作者:weehyong    | 项目源码 | 文件源码
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 = '  '))
项目:Modelingtools    作者:LMiceOrg    | 项目源码 | 文件源码
def GenerateCompData(self, cp_name, cp_ns, cp_desc, items):
        """ ???????? """

        node = self.GetNamespaceNode()
        cp_id = "%s.%s" %(cp_ns, cp_name)
        tnode = xmllib.SubElement(node, "Type", {"Id": cp_id,"Name":cp_name,
                                         "Uuid": self.dt.GetUuid(cp_ns, cp_name),
                                         "xsi:type":"Types:Structure",
                                         "Description":cp_desc} )
        for item in items:
            for i in range(len(item)):
                if item[i] == None:
                    item[i] = ""
                if type(item[i]) not in (str, unicode):
                    #print type(item[i]), type(item[i]) != unicode
                    item[i] = str(item[i])
            it_name, it_ns, it_cname, it_type, it_grain, it_unit, it_default, it_min, it_max, it_desc = item
            it_id = "%s.%s" %(cp_id, it_name)
            fnode = xmllib.SubElement(tnode, "Field", {"Id": it_id, "Name":it_name,
            "Description":it_desc, "Unit":it_unit, "ChineseName":it_cname, "GrainSize": it_grain,
            "Default":it_default, "Min":it_min, "Max":it_max})
            xmllib.SubElement(fnode, "Type", {"Namespace":it_ns, "Href":it_type,"HrefUuid":self.dt.GetUuid(it_ns, it_type) })
项目:Modelingtools    作者:LMiceOrg    | 项目源码 | 文件源码
def GenComposite(self):
        com = xmllib.SubElement(self.root, "Composite")
        #SubComponents
        scs = xmllib.SubElement(com, "SubComponents")
        #InterfaceConnections
        ics = xmllib.SubElement(com, "InterfaceConnections")
        #EventConnections
        ecs = xmllib.SubElement(com, "EventConnections")
        #PropertyMaps
        pms = xmllib.SubElement(com, "PropertyMaps")
        #InputsMap
        im = xmllib.SubElement(com, "InputsMap")
        #OutputsMap
        om = xmllib.SubElement(com, "OutputsMap")
        #End if Composite
    #Project:Resource
项目:Modelingtools    作者:LMiceOrg    | 项目源码 | 文件源码
def GenerateStruct(ns, root, etype, edesc, edict):
    iid = "%s.%s" %(ns, etype)
    node = xmllib.SubElement(root, "Type", {"Id": iid,"Name":etype,
                                     "Uuid": GenerateUUIDByName(iid),
                                            "Description":edesc,
                                     "xsi:type":"Types:Structure"} )
    for item in edict:
        ename, dtype, cname, evdesc = item
        iid = "%s.%s.%s" %(ns, etype, ename)
        field = xmllib.SubElement(node, "Field", {"Id":iid,"Name":ename})
        xmllib.SubElement(field, "Type", {"Namespace":"RTL",
                                          "Href":dtype,
                                          "HrefUuid":GenerateUUIDByName(dtype),
                                            "Description":evdesc})
        #print key

#Create XML Structure node
项目:Modelingtools    作者:LMiceOrg    | 项目源码 | 文件源码
def GenerateProjectImport2(self, pj_name, root):
        """all """
        ids = self.ds_nodes.keys()
        ids.sort()
        last_ns = ""
        nsd=autotools.l_ns_name
        nsnode = xmllib.SubElement(root, "Import", {"Id":nsd, "Name":nsd, "Location":nsd})
        for id in ids:
            ns, nm = id.split(".")
            if last_ns != ns:
                last_ns = ns

            tnode = self.ds_nodes[id]
            nsnode.append(tnode)
        ids = self.types.keys()
        ids.sort()
        for ns in ids:
            if last_ns != ns:
                last_ns = ns
                nsnode = xmllib.SubElement(root, "Import", {"Id":ns, "Name":ns,"Location":ns})
            for nm in self.types[ns].keys():
                t = self.types[ns][nm]
                tnode = xmllib.SubElement(nsnode, "Type", {"Id": t["Id"], "Name":t["Name"],
                                                           "Uuid":t["Uuid"], "xsi:type":t["xsi:type"] })
                xmllib.SubElement(tnode, "Description").text=t["Description"]
项目:Modelingtools    作者:LMiceOrg    | 项目源码 | 文件源码
def CreateEnumDataItem(self, node, data):
        """ ?????? """
        ed_ns = data.item_ns
        ctx = data.item_val
        ed_type, ed_desc, ed_items = ctx[:3]
        ed_id = "%s.%s" %(ed_ns, ed_type)
        tnode = xmllib.Element("Type", {"Id": ed_id,"Name":ed_type,
                                         "Uuid": self.GetTypeUuid(ed_type, ed_ns),
                                         "xsi:type":"Types:Enumeration"
                                         } )
        xmllib.SubElement(tnode, "Description").text = ed_desc
        #xmllib.SubElement(tnode, "Source").text = "%s[%s]" %(data.source, data.part_name)
        for item in ed_items:
            it_name, it_value, it_desc = item[:3]
            it_id = "%s.%s" %(ed_id, it_name)
            inode = xmllib.SubElement(tnode, "Literal", {"Id":it_id,"Name":it_name,
                                                "Value":str(int( it_value ) ) })
            xmllib.SubElement(inode, "Description").text = it_desc
        node.append(tnode)
        #cache type node
        self.datastructs[ed_id] = xmllib.tostring(tnode)
项目:visual_mpc    作者:febert    | 项目源码 | 文件源码
def create_xml(self):

        for i in range(self._hyperparams['num_objects']):
            xmldir = '/'.join(str.split(self._hyperparams['filename'], '/')[:-1])
            mass = np.random.uniform(.01, 1.)
            root = ET.Element("top")
            ET.SubElement(root, "inertial", pos="0 0 0", mass="{}".format(mass),
                          diaginertia="{0} {1} {2}".format(mass/2., mass/2., mass/2.))
            tree = ET.ElementTree(root)
            xml_str = minidom.parseString(ET.tostring(
                    tree.getroot(),
                    'utf-8')).toprettyxml(indent="    ")

            xml_str = xml_str.splitlines()[1:]
            xml_str = "\n".join(xml_str)

            with open(xmldir+"/mass{}.xml".format(i), "wb") as f:
                f.write(xml_str)
项目:pytorch_60min_blitz    作者:kyuhyoung    | 项目源码 | 文件源码
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='  '))
项目:pdb2uniprot    作者:mgalardini    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def test_matrix_without_begin_and_end(self):  # taken from MathJax
        table = eTree.SubElement(self.row, 'mtable')

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'a'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'b'

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'c'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'd'

        self.assertEqual(eTree.tostring(self.math), converter.convert(r'\matrix{a & b \\ c & d}'))
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def test_matrix_with_alignment(self):
        table = eTree.SubElement(self.row, 'mtable')

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'a'
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'b'

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'c'
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'd'

        self.assertEqual(eTree.tostring(self.math),
                         converter.convert(r'\begin{matrix*}[r]a & b \\ c & d \end{matrix*}'))
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def test_matrix_with_negative_sign(self):
        table = eTree.SubElement(self.row, 'mtable')

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mo = eTree.SubElement(td, 'mo')
        mo.text = '−'
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'a'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'b'

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'c'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'd'

        self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{matrix}-a & b \\ c & d \end{matrix}'))
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def test_pmatrix(self):
        mo = eTree.SubElement(self.row, 'mo')
        mo.text = '('
        table = eTree.SubElement(self.row, 'mtable')

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'a'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'b'

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'c'
        td = eTree.SubElement(tr, 'mtd')
        mi = eTree.SubElement(td, 'mi')
        mi.text = 'd'

        mo = eTree.SubElement(self.row, 'mo')
        mo.text = ')'
        self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{pmatrix}a & b \\ c & d \end{pmatrix}'))
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def test_simple_array(self):
        table = eTree.SubElement(self.row, 'mtable')

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd', columnalign='center')
        mn = eTree.SubElement(td, 'mn')
        mn.text = '1'
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mn = eTree.SubElement(td, 'mn')
        mn.text = '2'

        tr = eTree.SubElement(table, 'mtr')
        td = eTree.SubElement(tr, 'mtd', columnalign='center')
        mn = eTree.SubElement(td, 'mn')
        mn.text = '3'
        td = eTree.SubElement(tr, 'mtd', columnalign='right')
        mn = eTree.SubElement(td, 'mn')
        mn.text = '4'

        self.assertEqual(eTree.tostring(self.math),
                         converter.convert(r'\begin{array}{cr} 1 & 2 \\ 3 & 4 \end{array}'''))
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def _convert_matrix_content(param, parent, alignment=None):
    for row in param:
        mtr = eTree.SubElement(parent, 'mtr')
        iterable = iter(range(len(row)))
        for i in iterable:
            element = row[i]
            if alignment:
                column_align = {'r': 'right', 'l': 'left', 'c': 'center'}.get(alignment)
                mtd = eTree.SubElement(mtr, 'mtd', columnalign=column_align)
            else:
                mtd = eTree.SubElement(mtr, 'mtd')
            if isinstance(element, list):
                _classify_subgroup(element, mtd)
            elif element in COMMANDS:
                _convert_command(element, row, i, iterable, mtd)
            else:
                _classify(element, mtd)
项目:latex2mathml    作者:Code-ReaQtor    | 项目源码 | 文件源码
def _classify(_element, parent):
    symbol = convert_symbol(_element)
    if re.match('\d+(.\d+)?', _element):
        mn = eTree.SubElement(parent, 'mn')
        mn.text = _element
    elif _element in '+-*/()=':
        mo = eTree.SubElement(parent, 'mo')
        mo.text = _element if symbol is None else '&#x{};'.format(symbol)
    elif symbol and (int(symbol, 16) in range(int('2200', 16), int('22FF', 16) + 1) or
                     int(symbol, 16) in range(int('2190', 16), int('21FF', 16) + 1)):
        mo = eTree.SubElement(parent, 'mo')
        mo.text = '&#x{};'.format(symbol)
    elif _element.startswith('\\'):
        if symbol is not None:
            mi = eTree.SubElement(parent, 'mi')
            mi.text = '&#x{};'.format(symbol)
        else:
            e = _element.lstrip('\\')
            mi = eTree.SubElement(parent, 'mi')
            mi.text = e
    else:
        mi = eTree.SubElement(parent, 'mi')
        mi.text = _element
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
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()
项目:batch-shipyard    作者:Azure    | 项目源码 | 文件源码
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 = '  '))
项目:sketchfe    作者:ozymaxx    | 项目源码 | 文件源码
def toXML(self, name):
        sketch = ET.Element("sketch")
        sketch.attrib["id"] = str(self.sketch_id)

        for stk in self.strokes:
            for pnt in stk.points:
                ET.SubElement(sketch, "point", id = str(pnt.pid), time = str(pnt.time), x = str(pnt.x), y = str(pnt.y))

        for stk in self.strokes:
            stroke = ET.SubElement(sketch, "stroke")
            stroke.attrib["id"] = str(stk.sid)
            stroke.attrib["visible"] = "true"
            for pnt in stk.points:
                ET.SubElement(stroke, "arg", type = "point").text = str(pnt.pid)

        tree = ET.ElementTree(sketch)
        tree.write( os.path.join(os.getcwd(), 'XMLfiles', 'AfterTraining' , str(name) + ".xml") )

    # resamples the sketch before IDM feature extraction
项目:sketchfe    作者:ozymaxx    | 项目源码 | 文件源码
def toXML(self, name):
        sketch = ET.Element("sketch")
        sketch.attrib["id"] = str(self.sketch_id)

        for stk in self.strokes:
            for pnt in stk.points:
                ET.SubElement(sketch, "point", id = str(pnt.pid), time = str(pnt.time), x = str(pnt.x), y = str(pnt.y))

        for stk in self.strokes:
            stroke = ET.SubElement(sketch, "stroke")
            stroke.attrib["id"] = str(stk.sid)
            stroke.attrib["visible"] = "true"
            for pnt in stk.points:
                ET.SubElement(stroke, "arg", type = "point").text = str(pnt.pid)

        tree = ET.ElementTree(sketch)
        tree.write( os.path.join(os.getcwd(), 'XMLfiles', 'AfterTraining' , str(name) + ".xml") )

    # resamples the sketch before IDM feature extraction
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:vCloudDirectorManager    作者:blackms    | 项目源码 | 文件源码
def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
项目:bpmn-python    作者:KrzyHonk    | 项目源码 | 文件源码
def export_start_event_info(node_params, output_element):
        """
        Adds StartEvent attributes to exported XML element

        :param node_params: dictionary with given intermediate catch event parameters,
        :param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
        """
        output_element.set(consts.Consts.parallel_multiple, node_params.get(consts.Consts.parallel_multiple))
        output_element.set(consts.Consts.is_interrupting, node_params.get(consts.Consts.is_interrupting))
        definitions = node_params.get(consts.Consts.event_definitions)
        for definition in definitions:
            definition_id = definition[consts.Consts.id]
            definition_type = definition[consts.Consts.definition_type]
            output_definition = eTree.SubElement(output_element, definition_type)
            if definition_id != "":
                output_definition.set(consts.Consts.id, definition_id)
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
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
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
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
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
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:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush()
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
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
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
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
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
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:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush()
项目:django-cml    作者:ArtemiusUA    | 项目源码 | 文件源码
def export_orders(self):
        for order in self.item_processor.yield_item(Order):
            order_element = ET.SubElement(self.root, u'????????')
            ET.SubElement(order_element, u'??').text = six.text_type(order.id)
            ET.SubElement(order_element, u'?????').text = six.text_type(order.number)
            ET.SubElement(order_element, u'????').text = six.text_type(order.date.strftime('%Y-%m-%d'))
            ET.SubElement(order_element, u'?????').text = six.text_type(order.time.strftime('%H:%M:%S'))
            ET.SubElement(order_element, u'???????????').text = six.text_type(order.operation)
            ET.SubElement(order_element, u'????').text = six.text_type(order.role)
            ET.SubElement(order_element, u'??????').text = six.text_type(order.currency_name)
            ET.SubElement(order_element, u'????').text = six.text_type(order.currency_rate)
            ET.SubElement(order_element, u'?????').text = six.text_type(order.sum)
            ET.SubElement(order_element, u'???????????').text = six.text_type(order.comment)
            clients_element = ET.SubElement(order_element, u'???????????')
            client_element = ET.SubElement(clients_element, u'??????????')
            ET.SubElement(client_element, u'??').text = six.text_type(order.client.id)
            ET.SubElement(client_element, u'????????????').text = six.text_type(order.client.name)
            ET.SubElement(client_element, u'????').text = six.text_type(order.client.role)
            ET.SubElement(client_element, u'??????????????????').text = six.text_type(order.client.full_name)
            ET.SubElement(client_element, u'???????').text = six.text_type(order.client.last_name)
            ET.SubElement(client_element, u'???').text = six.text_type(order.client.first_name)
            address_element = ET.SubElement(clients_element, u'????????????????')
            ET.SubElement(clients_element, u'?????????????').text = six.text_type(order.client.address)
            products_element = ET.SubElement(order_element, u'??????')
            for order_item in order.items:
                product_element = ET.SubElement(products_element, u'?????')
                ET.SubElement(product_element, u'??').text = six.text_type(order_item.id)
                ET.SubElement(product_element, u'????????????').text = six.text_type(order_item.name)
                sku_element = ET.SubElement(product_element, u'?????????????? ')
                sku_element.set(u'???', order_item.sku.id)
                sku_element.set(u'??????????????????', order_item.sku.name_full)
                sku_element.set(u'???????????????????????', order_item.sku.international_abbr)
                sku_element.text = order_item.sku.name
                ET.SubElement(product_element, u'?????????????').text = six.text_type(order_item.price)
                ET.SubElement(product_element, u'??????????').text = six.text_type(order_item.quant)
                ET.SubElement(product_element, u'?????').text = six.text_type(order_item.sum)
项目:RedHat    作者:opencontrol    | 项目源码 | 文件源码
def xccdf_multiple_subelements(xccdftree, xccdf_element, yamlcontent, yaml_key):
    yaml_key = yaml_key_value(yamlcontent, yaml_key)
    value = ""
    attrib_type = "idref"
    attrib = "true"

    if yaml_key:
        if type(yaml_key) is dict:
            for key, val in yaml_key.iteritems():
                if val is None:
                    val = ""
                dict_element = ET.SubElement(xccdftree, xccdf_element)
                dict_element.set(key, val)

            return xccdftree

        if type(yaml_key) is list:
            for rules in yaml_key:
                if "item" in rules.keys():
                    value = rules["item"]
                if "rule" in rules.keys():
                    value = rules["rule"]

                if "option" in rules.keys():
                    for key, val in rules["option"].iteritems():
                        opt = ET.SubElement(xccdftree, xccdf_element)
                        opt.set(attrib_type, key)
                        opt.text = val
                else:
                    rule = ET.SubElement(xccdftree, xccdf_element)
                    rule.set(attrib_type, value)
                    if "selector" in rules.keys():
                        rule.set("selector", rules["selector"])
                    if "selected" in rules.keys():
                        rule.set("selected", str(rules["selected"]).lower())
                    else:
                        if "item" not in rules.keys():
                            rule.set("selected", "true")

    return xccdftree
项目:imcsdk    作者:CiscoUcs    | 项目源码 | 文件源码
def elem_create(self, class_tag, xml_doc=None, override_tag=None):
        if xml_doc is None:
            xml_obj = Element(class_tag)
        else:
            if override_tag:
                xml_obj = SubElement(xml_doc, override_tag)
            else:
                xml_obj = SubElement(xml_doc, class_tag)
        return xml_obj
项目:imcsdk    作者:CiscoUcs    | 项目源码 | 文件源码
def to_xml(self, xml_doc=None, option=None, cookie=None):
        """
        This method returns the xml element node for the current object
        with it's hierarchy.

        Args:
            xml_doc: document to which the Mo attributes are added.
                    Can be None.
            option: not required for Generic Mo class object

        Example:
            from imcmsdk.imcmo import GenericMo\n
            args = {"a": 1, "b": 2, "c":3}\n
            obj = GenericMo("testLsA", "org-root", **args)\n
            obj1 = GenericMo("testLsB", "org-root", **args)\n
            obj.add_child(obj1)\n
            elem = obj.write_xml()\n

            import imcmsdk.imcxmlcodec as xc\n
            xc.to_xml_str(elem)\n

        Output:
            '<testLsA a="1" b="2" c="3" dn="org-root/" rn="">\n
                <testLsB a="1" b="2" c="3" dn="org-root/" rn="" />\n
            </testLsA>'
        """

        if xml_doc is None:
            xml_obj = Element(imcgenutils.word_l(self._class_id))
        else:
            xml_obj = SubElement(xml_doc, imcgenutils.word_l(self._class_id))
        for key in self.__dict__:
            if not key.startswith('_'):
                xml_obj.set(key, getattr(self, key))
        self.child_to_xml(xml_obj)
        return xml_obj
项目:BlenderRobotDesigner    作者:HBPNeurorobotics    | 项目源码 | 文件源码
def SubElement(self, parent, tag, attrib=None):
        if not attrib:
            attrib = {}
        return etree.SubElement(parent, tag.format(ns=self.ns), attrib)
项目:BlenderRobotDesigner    作者:HBPNeurorobotics    | 项目源码 | 文件源码
def SubInstance(self, parent, element):
        tag = element.tag.replace(self.ns, '{ns}instance_')
        # self.logger.debug('tag: %s', tag)
        return self.SubElement(parent, tag,
                               attrib={'url': '#' + element.get('id'), 'sid': "inst_" + element.get('id')})
项目:EasyStorj    作者:lakewik    | 项目源码 | 文件源码
def save_sync_configuration(self, settings_ui):

        self.save_sync_directories(settings_ui.sync_directories_tableWidget)

        with open(SYNC_CONFIG_FILE, 'r') as conf_file:
            XML_conf_data = conf_file.read().replace('\n', '')

        tree = ET.parse(SYNC_CONFIG_FILE)

        #root = ET.Element("configuration")
        #doc = ET.SubElement(root, "client")

        # settings_ui = Ui_
        if settings_ui.sync_enabled_checkBox.isChecked():
            sync_enabled_checkbox = '1'
        else:
            sync_enabled_checkbox = '0'

        if settings_ui.start_sync_on_boot_checkBox.isChecked():
            start_sync_on_boot_checkbox = '1'
        else:
            start_sync_on_boot_checkbox = '0'

        if settings_ui.show_sync_tray_icon_checkBox.isChecked():
            show_sync_tray_icon_checkbox = '1'
        else:
            show_sync_tray_icon_checkbox = '0'


        tree.write(SYNC_CONFIG_FILE)
项目:EasyStorj    作者:lakewik    | 项目源码 | 文件源码
def save_account_credentials(self):
        root = ET.Element('account')
        doc = ET.SubElement(root, 'credentials')

        ET.SubElement(doc, 'login_email').text = str(self.login_email)
        ET.SubElement(doc, 'password').text = \
            str(hashlib.sha256(self.password.encode('ascii')).hexdigest())
        ET.SubElement(doc, 'logged_in').text = '1'
        tree = ET.ElementTree(root)
        tree.write('storj_account_conf.xml')
项目:EasyStorj    作者:lakewik    | 项目源码 | 文件源码
def logout(self):
        print "Log out action"
        root = ET.Element("account")
        doc = ET.SubElement(root, "credentials")
        ET.SubElement(doc, "login_email").text = "0"
        ET.SubElement(doc, "password").text = "0"
        ET.SubElement(doc, "logged_in").text = "0"
        tree = ET.ElementTree(root)
        tree.write(ACCOUNT_FILE)
        return True
项目:super_simple_siem    作者:elucidant    | 项目源码 | 文件源码
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