Python lxml.etree 模块,register_namespace() 实例源码

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

项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        ET.register_namespace("svg", self._SVG_namespace)
        super(SvgFragmentImage, self).__init__(*args, **kwargs)
        # Save the unit size, for example the default box_size of 10 is '1mm'.
        self.unit_size = self.units(self.box_size)
项目:filtered-alert-hub    作者:filtered-alert-hub    | 项目源码 | 文件源码
def makeItem(caproot,metadata):

    newitem = ET.Element("item")
    ET.register_namespace('dc', "http://purl.org/dc/elements/1.1/" )


    title = ET.SubElement(newitem, "title")
    link = ET.SubElement(newitem, "link")
    description = ET.SubElement(newitem, "description")
    category = ET.SubElement(newitem, "category")
    itempubDate = ET.SubElement(newitem, "pubDate")
    guid = ET.SubElement(newitem, "guid")
    creator = ET.SubElement(newitem, "{http://purl.org/dc/elements/1.1/}creator")
    itemdate = ET.SubElement(newitem, "{http://purl.org/dc/elements/1.1/}date")


    namespaces = {'cap': 'urn:oasis:names:tc:emergency:cap:1.1'}

    alerttime = dateutil.parser.parse(caproot.xpath("string(cap:sent/text())", namespaces=namespaces ))
    #print("got time {} from cap".format(alerttime))
    alerttime =  (alerttime - alerttime.utcoffset()).replace(tzinfo=None) if alerttime.utcoffset() else alerttime #convert to UTC
    #print("converted to  {} ".format(alerttime))


    title.text = caproot.xpath("string(cap:info/cap:headline/text())", namespaces=namespaces )
    link.text = metadata["link"]
    description.text = caproot.xpath("string(cap:info/cap:description/text())", namespaces=namespaces )
    itempubDate.text = alerttime.strftime("%a, %d %b %Y %H:%M:%S %z")
    itemdate.text = alerttime.isoformat()
    guid.text = caproot.xpath("string(cap:identifier/text())", namespaces=namespaces )

    sender = caproot.xpath("string(cap:sender/text())", namespaces=namespaces )
    senderName = caproot.xpath("string(cap:senderName/text())", namespaces=namespaces )

    creator.text =  "{} ({})".format(sender,senderName) if senderName else sender 
    category.text = ",".join(caproot.xpath("cap:info/cap:category/text()",namespaces=namespaces))

    return newitem
项目:wsma_python    作者:aradford123    | 项目源码 | 文件源码
def parseXML(xml_text):
        '''Parses given XML string and returns the 'response' child within the
        XML tree. If no response is found, the SOAP 'Envelope' is returned.

        If an empty string is used or an error occurs during parsing then
        dict(error='some error string') is returned.

        This still assumes that IF an XML string is passed into
        this function then it should have a valid SOAP Envelope.

        :param xml_text: XML string to be converted
        :rtype: dict
        '''
        if xml_text is None:
            return dict(error='XML body is empty')

        """
        from lxml import etree
        etree.register_namespace("SOAP", "http://schemas.xmlsoap.org/soap/envelope/")
        element = etree.fromstring(xml_text.encode('utf-8'))
        print('#' * 40)
        print(etree.tostring(element, pretty_print=True).decode('utf-8'))
        print(json.dumps(xmltodict.parse(xml_text), indent=4))
        """

        logging.debug("XML string: {}".format(xml_text))
        try:
            dom = parseString(xml_text)
        except ExpatError as e:
            return dict(error='%s' % e)

        logging.debug("XML tree:{}".format(dom.childNodes[-1].toprettyxml()))

        response = dom.getElementsByTagName('response')
        if len(response) > 0:
            return xmltodict.parse(response[0].toxml())

        return xmltodict.parse(
            dom.getElementsByTagNameNS(
                "http://schemas.xmlsoap.org/soap/envelope/",
                "Envelope")[0].toxml())
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        ET.register_namespace("svg", self._SVG_namespace)
        super(SvgFragmentImage, self).__init__(*args, **kwargs)
        # Save the unit size, for example the default box_size of 10 is '1mm'.
        self.unit_size = self.units(self.box_size)
项目:TornadoWeb    作者:VxCoder    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        ET.register_namespace("svg", self._SVG_namespace)
        super(SvgFragmentImage, self).__init__(*args, **kwargs)
        # Save the unit size, for example the default box_size of 10 is '1mm'.
        self.unit_size = self.units(self.box_size)
项目:caom2tools    作者:opencadc    | 项目源码 | 文件源码
def check_xml(xml_func, test_wcs, expected):
    etree.register_namespace(
        'caom2', 'http://www.opencadc.org/caom2/xml/v2.3')
    parent_element = etree.Element(
        '{http://www.opencadc.org/caom2/xml/v2.3}import')
    xml_func(test_wcs, parent_element)
    tree = etree.ElementTree(parent_element)
    result = etree.tostring(tree, encoding='unicode', pretty_print=True)
    assert result == expected, result