How to use the lxml.etree.XML 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 kamalgill / flask-appengine-template / src / packages / werkzeug / contrib / testtools.py View on Github external
def lxml(self):
        """Get an lxml etree if possible."""
        if ('html' not in self.mimetype and 'xml' not in self.mimetype):
            raise AttributeError('Not an HTML/XML response')
        from lxml import etree
        try:
            from lxml.html import fromstring
        except ImportError:
            fromstring = etree.HTML
        if self.mimetype=='text/html':
            return fromstring(self.data)
        return etree.XML(self.data)
    lxml = cached_property(lxml)
github STIXProject / stix-validator / validators / stix.py View on Github external
def _add_prohibited_test(self, rule_element, entity_name, context):
        '''Adds a test to the rule element checking for the presence of a prohibited STIX field.'''
        entity_path = "%s/%s" % (context, entity_name) if entity_name.startswith("@") else context
        text = "%s is prohibited by this profile" % (entity_path)
        test_field = entity_name if entity_name.startswith("@") else "true()"
        element = etree.XML('%s '
                            '[] '
                            % (self.NS_SCHEMATRON, test_field, text))
        rule_element.append(element)
github odoo / odoo / odoo / report / printscreen / ps_list.py View on Github external
def _parse_string(self, view):
        try:
            dom = etree.XML(view.encode('utf-8'))
        except Exception:
            dom = etree.XML(view)
        return self._parse_node(dom)
github QIICR / dcmqi / util / junit / convert.py View on Github external
from lxml import etree
import StringIO
import sys

TAGfile = open(sys.argv[1]+"/Testing/TAG", 'r')
dirname = TAGfile.readline().strip()

xmlfile = open(sys.argv[1]+"/Testing/"+dirname+"/Test.xml", 'r')
xslfile = open(sys.argv[2], 'r')

xmlcontent = xmlfile.read()
xslcontent = xslfile.read()

xmldoc = etree.parse(StringIO.StringIO(xmlcontent))
xslt_root = etree.XML(xslcontent)
transform = etree.XSLT(xslt_root)

result_tree = transform(xmldoc)
print(result_tree)
github AGProjects / python-sipsimple / sipsimple / payloads / __init__.py View on Github external
def _update_schema(cls):
        if cls.schema_map:
            location_map = {ns: urllib.quote(os.path.abspath(os.path.join(cls.schema_path, schema_file)).replace('\\', '//')) for ns, schema_file in cls.schema_map.iteritems()}
            schema = """
                
                    %s
                
            """ % '\r\n'.join('' % (namespace, schema_location) for namespace, schema_location in location_map.iteritems())
            cls.schema = etree.XMLSchema(etree.XML(schema))
            cls.parser = etree.XMLParser(schema=cls.schema, remove_blank_text=True)
        else:
            cls.schema = None
            cls.parser = etree.XMLParser(remove_blank_text=True)
github VAMDC / NodeSoftware / nodes / jpl / node / cdmsportalfunc.py View on Github external
from lxml import etree
    from urllib2 import urlopen

    url=url.replace('rad3d','XSAMS')
    url=url.replace('png','XSAMS')
    url=url.replace('xspcat','XSAMS')
    url=url.replace('spcat','XSAMS')

    try:
        content = urlopen(url)
    except:
        return "url - error: " + url

    try:
        xml = etree.XML(content.read())
        prefixmap = {'xsams' : xml.nsmap[None]}
    except:
        return "ERROR"
    
    xp = "//xsams:Molecule"
    response = ""

    html = ""
    try:
        for m in xml.xpath(xp ,namespaces=prefixmap):
            try:
                stoichiometricformula = m.xpath('./xsams:MolecularChemicalSpecies/xsams:StoichiometricFormula', namespaces=prefixmap)[0].text
                chemicalname = m.xpath('./xsams:MolecularChemicalSpecies/xsams:ChemicalName/xsams:Value', namespaces=prefixmap)[0].text
                structuralformula = m.xpath('./xsams:MolecularChemicalSpecies/xsams:OrdinaryStructuralFormula/xsams:Value', namespaces=prefixmap)[0].text
                inchikey = m.xpath('./xsams:MolecularChemicalSpecies/xsams:InChIKey', namespaces=prefixmap)[0].text
                comment = m.xpath('./xsams:MolecularChemicalSpecies/xsams:Comment', namespaces=prefixmap)[0].text<table class="full"><tbody></tbody></table>
github mapmint / mapmint / mapmint-services / ows-security / service.py View on Github external
if protected.count(name.lower())&gt;0:
                strToReplace+=''
            else:
                strToReplace+=''
        toReplaceFinal=''+strToReplace+''
        if request.keys().count('version')==0 or request["version"]!="1.3.0":
            toReplaceFinal=''+toReplaceFinal+''
            
        outputs["Result"]["value"]=outputs["Result"]["value"].replace('',''+toReplaceFinal)
    else:
        if request["service"].upper()=="WCS":
            conf["lenv"]["message"]=zoo._("Not allowed!")
            return zoo.SERVICE_FAILED

        outputs["Result"]["value"]=outputs["Result"]["value"].replace('none','https://www.opengis.net/def/security/1.0/cc/owsCommon')
        context0 = etree.XML(outputs["Result"]["value"])
        #root=context0.getroot()
        print &gt;&gt; sys.stderr,"******"
        print &gt;&gt; sys.stderr,context0
        print &gt;&gt; sys.stderr,context0.attrib
        print &gt;&gt; sys.stderr,"******"
        #
        if outputs["Result"]["value"].count("http://www.opengis.net/ows/1.1")&gt;0:
            owsSchema="http://www.opengis.net/ows/1.1"
        else:
            owsSchema="http://www.opengis.net/ows"
        requests=context0.xpath("/*/*/*[name()='ows:Operation']/*")
        #if len(requests)==0:
        #    requests=context0.xpath("/*/*[name()='ows:Operation']/*")
        print &gt;&gt; sys.stderr,requests
        for j in requests:
            name=j.xpath("name()")
github rapid7 / nexpose-client-python / nexpose / xml_utils.py View on Github external
def from_large_string(s):
    return etree.XML(s.encode('utf-8'))
github biocommons / eutils / eutils / helpers.py View on Github external
def efetch_gene_by_hgnc_name(name):
    esr = ESearchResultParser(esearch_gene_by_hgnc_name(name))
    if esr.Count == 0:
        return None
    for id in esr.IdList:
        xml = efetch_gene_by_id(id)
        doc = le.XML(xml)
        reply_hgnc = doc.xpath('/Entrezgene-Set/Entrezgene/Entrezgene_gene/Gene-ref/Gene-ref_locus/text()')[0]
        if reply_hgnc == name:
            return xml
        logging.debug('queried for gene %s, skipped reply for gene %s' % (name, reply_hgnc))
    raise LocusNCBIError("NCBI search returned %d replies for %s, and none were for this gene!" % (esr.Count, name))
github henryluki / readdaily / spider / parser.py View on Github external
def httpParser1(url):
	'''
	common:title link description 
	'''
	content=httpRequest(url)#发送请求
	parser=etree.XMLParser(encoding='utf-8',recover=True, strip_cdata=False)
	root = etree.XML(content,parser)
	descr=root.xpath(u"//description")
	title=root.xpath(u"//title") 
	link=root.xpath(u"//link")
	pubDate=root.xpath(u"//pubDate")
	article=title[0].text
	content=[]
	counter=0
	for t in range(len(title)):
		if t!=0 and t&lt;=7:
			num=8-t
			string=httpXpath(descr[num].text)
			newtime=datetime.datetime.strptime(pubDate[num].text[:25],"%a, %d %b %Y %H:%M:%S")
			newtime=newtime.strftime('%Y年%m月%d日 %H:%M:%S')
			arr={}
			arr['article']=article
			arr['title']=title[num].text