Python xml.etree.ElementTree.fromstring() Examples

The following are 30 code examples for showing how to use xml.etree.ElementTree.fromstring(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .

Example 1
Project: pkmeter   Author: pkkid   File: pkconfig.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, pkmeter, parent=None):
        with open(self.TEMPLATE) as tmpl:
            template = ElementTree.fromstring(tmpl.read())
        PKWidget.__init__(self, template, self, parent)
        self.pkmeter = pkmeter                          # Save reference to pkmeter
        self._init_window()                             # Init ui window elements
        self.values = self.load()                       # Active configuration values
        self.listitems = []                             # List of items in the sidebar
        self.datatable = self._init_datatable()         # Init reusable data table
        self.pconfigs = self._init_pconfigs()           # Reference to each plugin config
        self.setWindowFlags(Qt.Dialog)
        self.setWindowModality(Qt.ApplicationModal) 
Example 2
Project: pkmeter   Author: pkkid   File: pkconfig.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _init_datatable(self):
        template = ElementTree.fromstring("""
          <vframe>
            <hframe>
              <QLineEdit id='filter' name='input_xlarge' placeholder='Filter'/>
              <stretch/><pushbutton text='Refresh' click='refresh_datatable'/>
            </hframe>
            <vframe id='table'/>
          </vframe>""")
        # Build the datatable
        self.datatable_wrap = PKWidget(template, self)
        datatable = QtWidgets.QTableWidget(0, 3, parent=None)
        datatable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        datatable.setHorizontalHeaderLabels(['Variable', 'Value', 'Type   '])
        datatable.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Interactive)
        datatable.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        datatable.horizontalHeader().setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
        datatable.horizontalHeader().resizeSection(0, 200)
        datatable.verticalHeader().setVisible(False)
        datatable.verticalHeader().setDefaultSectionSize(19)
        datatable.setParent(self.datatable_wrap)
        self.datatable_wrap.manifest.table.layout().addWidget(datatable)
        # Connect the filter input
        self.datatable_wrap.manifest.filter.textChanged.connect(self.filter_datatable)
        return datatable 
Example 3
Project: sfdclib   Author: rbauction   File: metadata.py    License: MIT License 6 votes vote down vote up
def _retrieve_deploy_result(self, async_process_id):
        """ Retrieves status for specified deployment id """
        attributes = {
            'client': 'Metahelper',
            'sessionId': self._session.get_session_id(),
            'asyncProcessId': async_process_id,
            'includeDetails': 'true'
            }
        mt_request = msg.CHECK_DEPLOY_STATUS_MSG.format(**attributes)
        headers = {'Content-type': 'text/xml', 'SOAPAction': 'checkDeployStatus'}
        res = self._session.post(self._get_api_url(), headers=headers, data=mt_request)
        root = ET.fromstring(res.text)
        result = root.find(
            'soapenv:Body/mt:checkDeployStatusResponse/mt:result',
            self._XML_NAMESPACES)
        if result is None:
            raise Exception("Result node could not be found: %s" % res.text)

        return result 
Example 4
Project: sfdclib   Author: rbauction   File: metadata.py    License: MIT License 6 votes vote down vote up
def _retrieve_retrieve_result(self, async_process_id, include_zip):
        """ Retrieves status for specified retrieval id """
        attributes = {
            'client': 'Metahelper',
            'sessionId': self._session.get_session_id(),
            'asyncProcessId': async_process_id,
            'includeZip': include_zip
        }
        mt_request = msg.CHECK_RETRIEVE_STATUS_MSG.format(**attributes)
        headers = {'Content-type': 'text/xml', 'SOAPAction': 'checkRetrieveStatus'}
        res = self._session.post(self._get_api_url(), headers=headers, data=mt_request)
        root = ET.fromstring(res.text)
        result = root.find(
            'soapenv:Body/mt:checkRetrieveStatusResponse/mt:result',
            self._XML_NAMESPACES)
        if result is None:
            raise Exception("Result node could not be found: %s" % res.text)

        return result 
Example 5
Project: sfdclib   Author: rbauction   File: session.py    License: MIT License 6 votes vote down vote up
def login(self):
        url = self.construct_url(self.get_soap_api_uri())
        headers = {'Content-Type': 'text/xml', 'SOAPAction': 'login'}
        password = self._password
        if self._token:
            password += self._token
        data = SfdcSession._LOGIN_TMPL.format(**{'username': self._username, 'password': password})
        r = self.post(url, headers=headers, data=data)
        root = ET.fromstring(r.text)
        if root.find('soapenv:Body/soapenv:Fault', SfdcSession._XML_NAMESPACES):
            raise Exception("Could not log in. Code: %s Message: %s" % (
                root.find('soapenv:Body/soapenv:Fault/faultcode', SfdcSession._XML_NAMESPACES).text,
                root.find('soapenv:Body/soapenv:Fault/faultstring', SfdcSession._XML_NAMESPACES).text))
        self._session_id = root.find('soapenv:Body/d:loginResponse/d:result/d:sessionId', SfdcSession._XML_NAMESPACES).text
        server_url = root.find('soapenv:Body/d:loginResponse/d:result/d:serverUrl', SfdcSession._XML_NAMESPACES).text
        self._instance = re.search("""https://(.*).salesforce.com/.*""", server_url).group(1) 
Example 6
Project: python-esppy   Author: sassoftware   File: xml.py    License: Apache License 2.0 6 votes vote down vote up
def from_xml(data):
    '''
    Convert XML to ElementTree.Element

    Parameters
    ----------
    data : string
        The XML to parse

    Returns
    -------
    :class:`ElementTree.Element`

    '''
    try:
        return ET.fromstring(data)
    except:
        for i, line in enumerate(data.split('\n')):
            print(i+1, line)
        raise 
Example 7
Project: python-esppy   Author: sassoftware   File: connections.py    License: Apache License 2.0 6 votes vote down vote up
def message(self,message):
        if self.isHandshakeComplete == False:
            Connection.message(self,message)
            return

        #logging.info("MSG: " + message)

        xml = None
        o = None

        for c in message:
            if c == '{' or c == '[':
                o = json.loads(str(message))
                break
            elif c == '<':
                xml = ElementTree.fromstring(str(message))
                break

        if o != None:
            self.processJson(o)
        elif xml != None:
            self.processXml(xml) 
Example 8
Project: python-esppy   Author: sassoftware   File: schema.py    License: Apache License 2.0 6 votes vote down vote up
def from_xml(cls, data, session=None):
        '''
        Create schema field from XML definition

        Parameters
        ----------
        data : xml-string or ElementTree.Element
            The schema field XML definition
        session : requests.Session
            The ESP session object

        Returns
        -------
        :class:`SchemaField`

        '''
        out = cls('', type='double', key=False)
        out.session = session

        if isinstance(data, six.string_types):
            data = ET.fromstring(data)

        out._set_attributes(data.attrib)

        return out 
Example 9
Project: razzy-spinner   Author: rafasashi   File: internals.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, etree):
        r"""
        Initialize a new Element wrapper for ``etree``.

        If ``etree`` is a string, then it will be converted to an
        Element object using ``ElementTree.fromstring()`` first:

            >>> ElementWrapper("<test></test>")
            <Element "<?xml version='1.0' encoding='utf8'?>\n<test />">

        """
        if isinstance(etree, compat.string_types):
            etree = ElementTree.fromstring(etree)
        self.__dict__['_etree'] = etree 
Example 10
Project: threat_intel   Author: Yelp   File: alexaranking.py    License: MIT License 6 votes vote down vote up
def _extract_response_xml(self, domain, response):
        """Extract XML content of an HTTP response into dictionary format.

        Args:
            response: HTML Response objects
        Returns:
            A dictionary: {alexa-ranking key : alexa-ranking value}.
        """
        attributes = {}
        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
        try:
            xml_root = ET.fromstring(response._content)
            for xml_child in xml_root.findall('SD//'):
                if xml_child.tag in alexa_keys and \
                        alexa_keys[xml_child.tag] in xml_child.attrib:
                    attributes[xml_child.tag.lower(
                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]
        except ParseError:
            # Skip ill-formatted XML and return no Alexa attributes
            pass
        attributes['domain'] = domain
        return {'attributes': attributes} 
Example 11
Project: movistartv2xmltv   Author: ese   File: tva.py    License: GNU General Public License v2.0 6 votes vote down vote up
def channellist(self,clist):
        root = ET.fromstring(self.xmldata)
        services = root[0][0].findall("{urn:dvb:ipisdns:2006}SingleService")
        for i in services:
            channelid = i[1].attrib["ServiceName"]
            clist[channelid] = {}
            #clist[channelid]["logo"] = i[1].attrib["logoURI"]
            url = "http://172.26.22.23:2001/appclient/incoming/epg/MAY_1/imSer/"+channelid+".jpg"
            clist[channelid]["logo"] = url
            clist[channelid]["address"] = i[0][0].attrib["Address"]
            clist[channelid]["port"] = i[0][0].attrib["Port"]
            clist[channelid]["name"] = i[2][0].text
            clist[channelid]["shortname"] = i[2][1].text
            clist[channelid]["desc"] = i[2][2].text
            clist[channelid]["tags"] = i[2][3][0].text.split("/")
        return clist 
Example 12
Project: plugin.video.kmediatorrent   Author: jmarth   File: tvdb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def search(name, complete=False):
    from kmediatorrent.caching import shelf
    import hashlib
    search_hash = hashlib.sha1(name).hexdigest()
    with shelf("com.thetvdb.search.%s" % search_hash) as show:
        if not show:
            import re
            import xml.etree.ElementTree as ET
            from kmediatorrent.utils import url_get
            dom = ET.fromstring(url_get("%s/api/GetSeries.php" % BASE_URL, params={
                "seriesname": name,
            }, headers=HEADERS, with_immunicity=False))
            if not len(dom):
                return
            meta = dom2dict(dom[0])
            if not complete:
                return update_image_urls(meta)
            show.update(get(meta["id"]))
        return show 
Example 13
Project: plugin.video.kmediatorrent   Author: jmarth   File: tvdb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_all_meta(show_id):
    import xml.etree.ElementTree as ET
    from concurrent import futures
    from kmediatorrent.utils import url_get, joining

    def _get_all_meta():
        r = url_get("%s/all/%s.xml" % (show_base_url(show_id), LANG), headers=HEADERS, with_immunicity=False)
        dom = ET.fromstring(r)
        if not len(dom):
            return
        return update_image_urls(dom2dict(dom))
    with futures.ThreadPoolExecutor(max_workers=2) as pool:
        meta = pool.submit(_get_all_meta)
        banners = pool.submit(get_banners, show_id)
    meta = meta.result()
    meta["series"][0]["episodes"] = meta["episode"]
    meta = meta["series"][0]
    meta["banners"] = banners.result() or []
    return meta 
Example 14
Project: TGC-Designer-Tools   Author: chadrockey   File: OSMTGC.py    License: Apache License 2.0 6 votes vote down vote up
def addOSMFromXML(course_json, xml_data, options_dict={}, printf=print):
    printf("Adding OpenStreetMap from XML")
    op = overpy.Overpass()
    result = op.parse_xml(xml_data)

    printf("Determining the UTM Geo Projection for this area")
    # Find the lat and lon bounding box from the XML directly
    # Can't find the query bounds in overpy
    root = ET.fromstring(xml_data)
    for bounds in root.iter('bounds'):
        latmin = float(bounds.get('minlat'))
        latmax = float(bounds.get('maxlat'))
        lonmin = float(bounds.get('minlon'))
        lonmax = float(bounds.get('maxlon'))
        break
    
    # Create a basic geopointcloud to handle this projection
    pc = GeoPointCloud()
    pc.addFromLatLon((latmin, lonmin), (latmax, lonmax), printf=printf)

    trees = addOSMToTGC(course_json, pc, result, x_offset=float(options_dict.get('adjust_ew', 0.0)), y_offset=float(options_dict.get('adjust_ns', 0.0)), \
                options_dict=options_dict, printf=printf)

    return course_json, trees 
Example 15
Project: PoseWarper   Author: facebookresearch   File: zipreader.py    License: Apache License 2.0 6 votes vote down vote up
def xmlread(filename):
    global _xml_path_zip
    global _xml_zfile
    path = filename
    pos_at = path.index('@')
    if pos_at == -1:
        print("character '@' is not found from the given path '%s'"%(path))
        assert 0
    path_zip = path[0: pos_at]
    path_xml = path[pos_at + 2:]
    if not os.path.isfile(path_zip):
        print("zip file '%s' is not found"%(path_zip))
        assert 0
    for i in xrange(len(_xml_path_zip)):
        if _xml_path_zip[i] == path_zip:
            data = _xml_zfile[i].open(path_xml)
            return ET.fromstring(data.read())
    _xml_path_zip.append(path_zip)
    print("read new xml file '%s'"%(path_zip))
    _xml_zfile.append(zipfile.ZipFile(path_zip, 'r'))
    data = _xml_zfile[-1].open(path_xml)
    return ET.fromstring(data.read()) 
Example 16
Project: terraform-templates   Author: PaloAltoNetworks   File: userid.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, device, prefix="", ignore_dup_errors=True):
        # Create a class logger
        self._logger = getlogger(__name__ + "." + self.__class__.__name__)
        self.device = device
        self.prefix = prefix
        self.ignore_dup_errors = ignore_dup_errors

        # Build the initial uid-message
        self._uidmessage = ET.fromstring("<uid-message>" +
                                         "<version>1.0</version>" +
                                         "<type>update</type>" +
                                         "<payload/>" +
                                         "</uid-message>")
        # Batch state
        self._batch = False
        self._batch_uidmessage = deepcopy(self._uidmessage) 
Example 17
Project: vulscan   Author: vulscanteam   File: 41-weblogic-2018-2894.py    License: MIT License 6 votes vote down vote up
def get_current_work_path(host):
    geturl = host + "/ws_utc/resources/setting/options/general"
    ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0'}
    request = requests.get(geturl)
    values = []
    if request.status_code == 404:
        exit("{} 404 not found".format(geturl))
    elif "Deploying Application".lower() in request.text.lower():
        print("First Deploying waiting a moment")
        time.sleep(30)
        request = requests.get(geturl, headers=ua)
    if "</defaultValue>" in request.content:
        root = ET.fromstring(request.content)
        value = root.find("section").find("options")
        for e in value:
            for sub in e:
                if e.tag == "parameter" and sub.tag == "defaultValue":
                    values.append(sub.text)
    if values:
        return values[0]
    else:
        exit(request.content) 
Example 18
Project: EliIE   Author: Tian312   File: retrieve_texts.py    License: MIT License 6 votes vote down vote up
def extract_criteria(cid):   #Using IDs to retrieve eligibility criteria
    output = ""
    if cid is not None:
        url_trial = 'http://clinicaltrials.gov/show/%s?displayxml=true'
        #url_trial ='http://clinicaltrials.gov/search?term=%s&displayxml=true'
        page = download_web_data(url_trial % cid)
        #with codecs.open('temp.txt', 'w','utf8') as writer:
        #    writer.write(page)
        #with codec.open('temp.txt', 'r', 'utf8') as reader:
        if page is not None:
            ct_xml = xml_parser.fromstring (page)
            ec = ct_xml.find ('eligibility')
            if ec is not None:
                # parse to get criteria text
                d = ec.find ('criteria')
                if d is not None:
                    txt = d.find ('textblock')
                    if txt is not None:
                        output = txt.text
    return output 
Example 19
Project: EliIE   Author: Tian312   File: retrieve_texts.py    License: MIT License 6 votes vote down vote up
def extract_description(cid):   #Using IDs to retrieve eligibility criteria
    output = ""
    if cid is not None:
        url_trial = 'http://clinicaltrials.gov/show/%s?displayxml=true'
        #url_trial ='http://clinicaltrials.gov/search?term=%s&displayxml=true'
        page = download_web_data(url_trial % cid)
        #with codecs.open('temp.txt', 'w','utf8') as writer:
        #    writer.write(page)
        #with codec.open('temp.txt', 'r', 'utf8') as reader:
        if page is not None:
            ct_xml = xml_parser.fromstring (page)
            summary = ct_xml.find ('brief_summary')
            if summary is not None:
                txt = summary.find ('textblock')
                if txt is not None:
                     output = txt.text
            description = ct_xml.find('detailed_description')
            if description is not None:
                txt2 = summary.find('textblock')
                if txt2 is not None:
                    output = output+txt2.text

    return output 
Example 20
Project: EliIE   Author: Tian312   File: fetch_disease_trial_mapping.py    License: MIT License 6 votes vote down vote up
def extract_criteria(cid):   #Using IDs to retrieve eligibility criteria
    output = ""
    if cid is not None:
        url_trial = 'http://clinicaltrials.gov/show/%s?displayxml=true'
        #url_trial ='http://clinicaltrials.gov/search?term=%s&displayxml=true'
        page = download_web_data(url_trial % cid)
        #with codecs.open('temp.txt', 'w','utf8') as writer:
        #    writer.write(page)
        #with codec.open('temp.txt', 'r', 'utf8') as reader:
        if page is not None:
            ct_xml = xml_parser.fromstring (page)
            ec = ct_xml.find ('eligibility')
            if ec is not None:
                # parse to get criteria text
                d = ec.find ('criteria')
                if d is not None:
                    txt = d.find ('textblock')
                    if txt is not None:
                        output = txt.text
    return output


#============== 
Example 21
Project: rucio   Author: rucio   File: webdav.py    License: Apache License 2.0 6 votes vote down vote up
def get_space_usage(self):
        """
        Get RSE space usage information.

        :returns: a list with dict containing 'totalsize' and 'unusedsize'

        :raises ServiceUnavailable: if some generic error occured in the library.
        """
        endpoint_basepath = self.path2pfn('')
        headers = {'Depth': '0'}

        try:
            root = ET.fromstring(self.session.request('PROPFIND', endpoint_basepath, verify=False, headers=headers, cert=self.session.cert).text)
            usedsize = root[0][1][0].find('{DAV:}quota-used-bytes').text
            try:
                unusedsize = root[0][1][0].find('{DAV:}quota-available-bytes').text
            except Exception as error:
                print('No free space given, return -999')
                unusedsize = -999
            totalsize = int(usedsize) + int(unusedsize)
            return totalsize, unusedsize
        except Exception as error:
            raise exception.ServiceUnavailable(error) 
Example 22
Project: rucio   Author: rucio   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def parse_replicas_from_string(string):
    """
    Parses the output of list_replicas from a json or metalink string
    into a dictionary. Metalink parsing is tried first and if it fails
    it tries to parse json.

    :param string: the string to parse

    :returns: a list with a dictionary for each file
    """
    try:
        root = ElementTree.fromstring(string)
        return parse_replicas_metalink(root)
    except ElementTree.ParseError as xml_err:
        try:
            return json.loads(string)
        except ValueError as json_err:
            raise MetalinkJsonParsingError(string, xml_err, json_err) 
Example 23
Project: yasha   Author: kblomqvist   File: test_parsers_svd.py    License: MIT License 6 votes vote down vote up
def test_register_folding_commaseparated_index():
    r = cmsis.SvdRegister(et.fromstring(
        """
        <register>
            <dim>3</dim>
            <dimIncrement>4</dimIncrement>
            <dimIndex>A,B,C</dimIndex>
            <name>GPIO_%s</name>
            <addressOffset>4</addressOffset>
        </register>
        """
    ))
    a = r.fold()

    assert len(a) == 3
    assert a[0].name == "GPIO_A"
    assert a[1].name == "GPIO_B"
    assert a[2].name == "GPIO_C" 
Example 24
Project: yasha   Author: kblomqvist   File: test_parsers_svd.py    License: MIT License 6 votes vote down vote up
def test_register_is_dimensionless_after_fold_up():
    r = cmsis.SvdRegister(et.fromstring(
        """
        <register>
            <dim>4</dim>
            <dimIncrement>4</dimIncrement>
            <dimIndex>3-6</dimIndex>
            <name>IRQ%s</name>
            <addressOffset>4</addressOffset>
        </register>
        """
    ))
    for r in r.fold():
        assert r.dim == None
        assert r.dimIndex == None
        assert r.dimIncrement == None 
Example 25
Project: pkmeter   Author: pkkid   File: plugin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _init_template(self):
        with open(self.TEMPLATE) as tmpl:
            template = ElementTree.fromstring(tmpl.read())
        return template 
Example 26
Project: pkmeter   Author: pkkid   File: about.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, parent=None):
        with open(self.TEMPLATE) as tmpl:
            template = ElementTree.fromstring(tmpl.read())
        PKWidget.__init__(self, template, self, parent)
        self.setWindowTitle('About PKMeter')
        self.setWindowFlags(Qt.Dialog)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowIcon(QtGui.QIcon(QtGui.QPixmap('img:logo.png')))
        self.layout().setContentsMargins(0,0,0,0)
        self.layout().setSpacing(0)
        self._init_stylesheet()
        self.manifest.version.setText('Version %s' % VERSION)
        self.manifest.qt.setText('QT v%s, PyQT v%s' % (QT_VERSION_STR, PYQT_VERSION_STR)) 
Example 27
Project: robosuite   Author: StanfordVL   File: mjcf_utils.py    License: MIT License 5 votes vote down vote up
def postprocess_model_xml(xml_str):
    """
    This function postprocesses the model.xml collected from a MuJoCo demonstration
    in order to make sure that the STL files can be found.
    """

    path = os.path.split(robosuite.__file__)[0]
    path_split = path.split("/")

    # replace mesh and texture file paths
    tree = ET.fromstring(xml_str)
    root = tree
    asset = root.find("asset")
    meshes = asset.findall("mesh")
    textures = asset.findall("texture")
    all_elements = meshes + textures

    for elem in all_elements:
        old_path = elem.get("file")
        if old_path is None:
            continue
        old_path_split = old_path.split("/")
        ind = max(
            loc for loc, val in enumerate(old_path_split) if val == "robosuite"
        )  # last occurrence index
        new_path_split = path_split + old_path_split[ind + 1 :]
        new_path = "/".join(new_path_split)
        elem.set("file", new_path)

    return ET.tostring(root, encoding="utf8").decode("utf8") 
Example 28
Project: robosuite   Author: StanfordVL   File: tune_camera.py    License: MIT License 5 votes vote down vote up
def modify_xml_for_camera_movement(xml, camera_name):
    """
    Cameras in mujoco are 'fixed', so they can't be moved by default.
    Although it's possible to hack position movement, rotation movement
    does not work. An alternative is to attach a camera to a mocap body,
    and move the mocap body.

    This function modifies the camera with name @camera_name in the xml
    by attaching it to a mocap body that can move around freely. In this
    way, we can move the camera by moving the mocap body.

    See http://www.mujoco.org/forum/index.php?threads/move-camera.2201/ for
    further details.
    """
    tree = ET.fromstring(xml)
    wb = tree.find("worldbody")

    # find the correct camera
    camera_elem = None
    cameras = wb.findall("camera")
    for camera in cameras:
        if camera.get("name") == camera_name:
            camera_elem = camera
            break
    assert(camera_elem is not None)

    # add mocap body
    mocap = ET.SubElement(wb, "body")
    mocap.set("name", "cameramover")
    mocap.set("mocap", "true")
    mocap.set("pos", camera.get("pos"))
    mocap.set("quat", camera.get("quat"))
    new_camera = ET.SubElement(mocap, "camera")
    new_camera.set("mode", "fixed")
    new_camera.set("name", camera.get("name"))
    new_camera.set("pos", "0 0 0")

    # remove old camera element
    wb.remove(camera_elem)

    return ET.tostring(tree, encoding="utf8").decode("utf8") 
Example 29
Project: bioservices   Author: cokelaer   File: xmltools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, data, encoding="utf-8"):
        """.. rubric:: Constructor

        :param data: an XML document format
        :param fixing_unicode: use only with HGNC service to fix issue with the
            XML returned by that particular service. No need to use otherwise.
            See :class:`~bioservices.hgnc.HGNC` documentation for details.
        :param encoding: default is utf-8 used. Used to fix the HGNC XML only.


        The data parameter must be a string containing the XML document. If you
        have an URL instead, use :class:`readXML`

        """
        #if fixing_unicode:
        #    x = unicodefix.FixingUnicode(data, verbose=False, encoding=encoding)
        #    self.data = x.fixed_string.encode("utf-8")
        #else:
        self.data = data[:]

        try:
            self.root = ET.fromstring(self.data)
        except:
            self.root = self.data[:]
        self._soup = None
        self.prettify = self.soup.prettify
        self.findAll = self.soup.findAll 
Example 30
Project: bioservices   Author: cokelaer   File: xmltools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, obj):
        """obj can be easyXML data set"""
        from lxml import objectify
        try:
            self.root = objectify.fromstring(obj.data)
        except:
            # try something else
            self.root = objectify.fromstring(obj)
        self.obj = obj