How to use the lxml.etree.ElementTree function in lxml

To help you get started, we’ve selected a few lxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github BillBarry / pyqwc / tests / qbxml.py View on Github external
if not iteratorID:
        attributes['iterator'] = "Start"
    else:
        attributes['iterator'] = "Continue"
        attributes['iteratorID'] = iteratorID        
    attributes['requestID'] = str(requestID)
    root = etree.Element("QBXML")
    root.addprevious(etree.ProcessingInstruction("qbxml", "version=\"8.0\""))
    msg = etree.SubElement(root,'QBXMLMsgsRq', {'onError':'stopOnError'})
    irq = etree.SubElement(msg,querytype+'QueryRq',attributes)
    mrt = etree.SubElement(irq,'MaxReturned')
    mrt.text= str(number_of_documents_to_retrieve_in_each_iteration)
    if querytype == 'Invoices':
        incitems = etree.SubElement(irq,'IncludeLineItems')
        incitems.text="true"
    tree = etree.ElementTree(root)
    requestxml = etree.tostring(tree, xml_declaration=True, encoding='UTF-8')
    return requestxml
github SymbiFlow / symbiflow-arch-defs / xc / common / utils / prjxray_create_equiv_tiles.py View on Github external
)

    cell_names = {}
    site_type_ports = {}

    for site_type_pkey in site_type_pkeys:
        cur.execute(
            "SELECT name FROM site_type WHERE pkey = ?", (site_type_pkey, )
        )
        site_type = cur.fetchone()[0]
        site_prefix = site_prefixes[site_type_pkey]
        site_type_path = site_pbtype.format(
            site_type.lower(), site_type.lower()
        )

        cell_pb_type = ET.ElementTree()
        root_element = cell_pb_type.parse(site_type_path)
        cell_names[site_type] = root_element.attrib['name']

        ports = {}
        for inputs in root_element.iter('input'):
            ports[inputs.attrib['name']] = int(inputs.attrib['num_pins'])

        for clocks in root_element.iter('clock'):
            ports[clocks.attrib['name']] = int(clocks.attrib['num_pins'])

        for outputs in root_element.iter('output'):
            ports[outputs.attrib['name']] = int(outputs.attrib['num_pins'])

        assert site_type not in site_type_ports, (
            site_type, site_type_ports.keys()
        )
github Ghini / ghini.desktop / bauble / plugins / imex_xml / __init__.py View on Github external
results = table.select().execute().fetchall()
            columns = table.c.keys()
            try:
                for row in results:
                    row_el = ElementFactory(table_el, 'row')
                    for col in columns:
                        ElementFactory(row_el, 'column', attrib={'name': col},
                                       text=row[col])
            except ValueError, e:
                utils.message_details_dialog(utils.xml_safe_utf8(e),
                                             traceback.format_exc(),
                                             gtk.MESSAGE_ERROR)
                return
            else:
                if one_file:
                    tree = etree.ElementTree(tableset_el)
                    filename = os.path.join(path, '%s.xml' % table_name)
                    # TODO: can figure out why this keeps crashing
                    tree.write(filename, encoding='utf8', xml_declaration=True)


        if not one_file:
            tree = etree.ElementTree(tableset_el)
            filename = os.path.join(path, 'bauble.xml')
            tree.write(filename, encoding='utf8', xml_declaration=True)
github arskom / spyne / src / rpclib / util / model_utils.py View on Github external
def to_file(self, file_path):
        """Writes a model instance to a XML document

        @param The output file path for the xml file
        """

        el = self.to_etree()

        f = open(file_path, "w")

        etree.ElementTree(el).write(
            f,
            pretty_print=True,
            encoding="UTF-8",
            xml_declaration=True
            )

        f.close()
github daniel-de-vries / OpenLEGO / examples / pipeline / wing_opt.py View on Github external
load_cases : list of (float, float, float), optional
            List of load cases in the form of tuples with (Mach number, altitude, load factor).
    """
    from openlego.utils.xml_utils import xml_safe_create_element
    from openlego.test_suite.test_examples.wing_opt.kb.disciplines.xpaths import x_m_fixed, x_m_payload, x_m_mlw, \
        x_f_m_sys, x_f_m_wings, x_R, x_SFC, x_m_fuel_res, x_CDfus, x_CDother, \
        x_m_fuel_init, x_sigma_yield, x_m_wing_init, x_S_ref_init, x_CL_buffet, \
        x_M, x_H, x_n, x_ml_timeout, \
        x_c, x_tc, x_epsilon, x_b, x_Lambda, x_Gamma, x_xsi_fs, \
        x_xsi_rs, x_t_fs, x_t_rs, x_t_ts, x_t_bs, x_incidence, x_t_skin, x_rho_skin
    from lxml import etree
    variables = get_variables(n_wing_segments)

    root = etree.Element('cpacs')
    doc = etree.ElementTree(root)

    xml_safe_create_element(doc, x_c, variables['c']['value'])
    xml_safe_create_element(doc, x_tc, variables['tc']['value'])
    xml_safe_create_element(doc, x_epsilon, variables['epsilon']['value'])
    xml_safe_create_element(doc, x_b, variables['b']['value'])
    xml_safe_create_element(doc, x_Lambda, variables['Lambda']['value'])
    xml_safe_create_element(doc, x_Gamma, variables['Gamma']['value'])
    xml_safe_create_element(doc, x_xsi_fs, variables['xsi_fs']['value'])
    xml_safe_create_element(doc, x_xsi_rs, variables['xsi_rs']['value'])
    xml_safe_create_element(doc, x_t_fs, variables['t_fs']['value'])
    xml_safe_create_element(doc, x_t_rs, variables['t_rs']['value'])
    xml_safe_create_element(doc, x_t_ts, variables['t_ts']['value'])
    xml_safe_create_element(doc, x_t_bs, variables['t_bs']['value'])

    xml_safe_create_element(doc, x_incidence, variables['incidence']['value'])
    xml_safe_create_element(doc, x_t_skin, variables['t_skin']['value'])
github cyberbotics / webots / resources / sumo_exporter / exporter.py View on Github external
Crossroad.crossroads.append(crossroad)
        road.endJunction = crossroad
        road.endJunctionID = crossroad.id

# Export to SUMO nodes file
nodes = ET.Element('nodes')
for crossroad in Crossroad.crossroads:
    crossroad.create_node(nodes)
tree = ET.ElementTree(nodes)
tree.write(nodesFilePath, encoding='utf-8', xml_declaration=True, pretty_print=True)

# Export to SUMO edges file
edges = ET.Element('edges')
for road in Road.roads:
    road.create_edge(edges)
tree = ET.ElementTree(edges)
tree.write(edgesFilePath, encoding='utf-8', xml_declaration=True, pretty_print=True)

# Export SUMO configuration file
configuration = ET.Element('configuration')
tree = ET.ElementTree(configuration)
input = ET.SubElement(configuration, 'input')
ET.SubElement(input, 'net-file', value='sumo.net.xml')
ET.SubElement(input, 'route-files', value='sumo.rou.xml')
time = ET.SubElement(configuration, 'time')
ET.SubElement(time, 'begin', value='0')
report = ET.SubElement(configuration, 'report')
ET.SubElement(report, 'verbose', value='true')
ET.SubElement(report, 'no-step-log', value='true')
tree.write(configFilePath, encoding='utf-8', xml_declaration=True, pretty_print=True)
github skylander86 / lambda-text-extractor / lib-linux_x64 / lxml / html / soupparser.py View on Github external
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
    """Parse a file into an ElemenTree using the BeautifulSoup parser.

    You can pass a different BeautifulSoup parser through the
    `beautifulsoup` keyword, and a diffent Element factory function
    through the `makeelement` keyword.  By default, the standard
    ``BeautifulSoup`` class and the default factory of `lxml.html` are
    used.
    """
    if not hasattr(file, 'read'):
        file = open(file)
    root = _parse(file, beautifulsoup, makeelement, **bsargs)
    return etree.ElementTree(root)
github NYRDS / remixed-dungeon / tools / tx / tx2as.py View on Github external
#         newEntry.text = arrayItemText
                #         transifexData.append(newEntry)
                #
                #         arrayIndex = arrayIndex + 1
                #         arrayItem.text = "@string/"+stringItemName
                #
                #     jsonData.write(unescape(json.dumps(arrayDesc, ensure_ascii=False)))
                #     jsonData.write("\n")
                #     transifexData.remove(entry)
                #     if locale_code == 'en':
                #         arrays.append(entry)

                entry.text = processText(entry.text)

            indent(transifexData)
            ElementTree.ElementTree(transifexData).write(resource_dir + "/" + resource_name, encoding="utf-8", method="xml")
            jsonData.close()

            # if locale_code == 'en':
            #     indent(arrays)
            #     ElementTree.ElementTree(arrays).write(resource_dir + "/string_arrays.xml", encoding="utf-8", method="xml")

        except ElementTree.ParseError as error:
            print("shit happens with " + currentFilePath)
            print(error)

pprint.pprint(totalCounter)
github ferventdesert / etlpy / src / xspider.py View on Github external
def get_main(html,is_html=False):
    root= spider._get_etree(html);
    tree = etree.ElementTree(root);
    node_path = search_text_root(tree, root);
    nodes = tree.xpath(node_path);
    if len(nodes)==0:
        return ''
    node=nodes[0]
    if is_html:
        res = etree.tostring(node).decode('utf-8');
    else:
        if hasattr(node, 'text'):
            res = spider.get_node_text(node);
        else:
            res = extends.to_str(node)
    return res;
github chronitis / curseradio / curseradio / curseradio.py View on Github external
def save_favourites(self):
        path = xdg.BaseDirectory.save_data_path("curseradio")
        if self.favourites.dirty:
            opmlpath = pathlib.Path(path, "favourites.opml")
            opml = lxml.etree.ElementTree(self.favourites.to_xml())
            opml.write(str(opmlpath))