Python lxml.etree 模块,CDATA 实例源码

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

项目:sublime-atomizr    作者:idleberg    | 项目源码 | 文件源码
def write_xml(input):
        """Writes Sublime Text snippets (Plist)"""
        from lxml import etree

        completions = input["completions"][0]

        data = etree.Element("snippet")
        content = etree.SubElement(data, "content")
        content.text = etree.CDATA(input["completions"][0]["contents"])
        tabTrigger = etree.SubElement(data, "tabTrigger")
        tabTrigger.text = input["completions"][0]['trigger']
        scope = etree.SubElement(data, "scope")
        scope.text = input["scope"]

        if 'description' in input['completions'][0]:
            description = etree.SubElement(data, "description")
            description.text = input["completions"][0]["description"]

        output = etree.tostring(data, pretty_print=True, encoding="utf-8").decode('utf-8')

        return output
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def GetAttributeValue(attr, extract=True):
    """
    Function that extracts data from a tree node
    @param attr: tree node containing data to extract
    @param extract: attr is a tree node or not
    @return: data extracted as string
    """
    if not extract:
        return attr
    if len(attr.childNodes) == 1:
        return unicode(unescape(attr.childNodes[0].data))
    else:
        # content is a CDATA
        text = u''
        for node in attr.childNodes:
            if not (node.nodeName == "#text" and node.data.strip() == u''):
                text += unicode(unescape(node.data))
        return text
项目:Taigabot    作者:FrozenPigs    | 项目源码 | 文件源码
def test_cdata(self):
        wrapped = E.b(etree.CDATA('Hello'))
        self.assertEqual(_bytes('<b><![CDATA[Hello]]></b>'), etree.tostring(wrapped))
项目:Taigabot    作者:FrozenPigs    | 项目源码 | 文件源码
def test_cdata_solo(self):
        self.assertRaises(ValueError, E.b, 'Hello', etree.CDATA('World'))
项目:correios    作者:olist    | 项目源码 | 文件源码
def add_text_argument(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        text = kwargs.pop("text", None)
        cdata = kwargs.pop("cdata", None)
        element = f(*args, **kwargs)
        if cdata:
            element.text = etree.CDATA(cdata)
        elif text:
            element.text = text
        else:
            element.text = None
        return element

    return wrapper
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def GenerateAnyInfos(infos):

    def GetTextElement(tree):
        if infos["namespace"][0] == "##any":
            return tree.xpath("p")[0]
        return tree.xpath("ns:p", namespaces={"ns": infos["namespace"][0]})[0]

    def ExtractAny(tree):
        return GetTextElement(tree).text

    def GenerateAny(tree, value):
        GetTextElement(tree).text = etree.CDATA(value)

    def InitialAny():
        if infos["namespace"][0] == "##any":
            element_name = "p"
        else:
            element_name = "{%s}p" % infos["namespace"][0]
        p = etree.Element(element_name)
        p.text = etree.CDATA("")
        return p

    return {
        "type": COMPLEXTYPE,
        "extract": ExtractAny,
        "generate": GenerateAny,
        "initial": InitialAny,
        "check": lambda x: isinstance(x, (StringType, UnicodeType, etree.ElementBase))
    }
项目:weixincrop    作者:tonghou23    | 项目源码 | 文件源码
def response_xml(message):
    xml = etree.Element("xml")
    sub = etree.Element(key)
    sub.text= etree.CDATA(value)
项目:weixincrop    作者:tonghou23    | 项目源码 | 文件源码
def data_to_xml(msg,data):
    if 'ToUserName' not in data:
        data['ToUserName'] = msg['FromUserName']
    if 'FromUserName' not in data:
        data['FromUserName'] = msg['ToUserName']
    if 'CreateTime' not in data:
        data['CreateTime'] = int(time.time())

    xml = etree.Element("xml")

    def parsesub(key,value):
        if type(value) is str or type(value) is unicode:
            sub = etree.Element(key)
            sub.text= etree.CDATA(value)
            return sub
        if type(value) is int:
            sub = etree.Element(key)
            sub.text= '%d' % value
            return sub

        if type(value) is dict:
            sub = etree.Element(key)
            for sub_key,sub_value in value.items():
                sub.append(parsesub(sub_key,sub_value))
            return sub

        if type(value) is list:
            sub = etree.Element(key)
            for item in value:
                sub.append(parsesub('item',item))
            return sub

    for key,value in data.items():
        xml.append(parsesub(key,value))

    data = etree.tostring(xml,encoding='UTF-8')
    return data
项目:mzidentml_writer    作者:mobiusklein    | 项目源码 | 文件源码
def write(self, xml_file):
        with self.element.element(xml_file, with_id=True):
            if self.site_regexp is not None:
                regex = _element("SiteRegexp").element()
                regex.text = etree.CDATA(self.site_regexp)
                xml_file.write(regex)
            with element(xml_file, "EnzymeName"):
                self.context.param(self.name)(xml_file)
项目:fnapy    作者:alexandriagroup    | 项目源码 | 文件源码
def create_offer_element(offer_data):
    """Create an offer element

    An offer needs at least one offer_reference (SKU) and any other parameter
    accepted by the service (cf documentation)
    :param offer_reference: a seller offer reference (such as SKU)
    :param product_reference: a product reference (such as EAN)
    :param product_state: a product state
    :param price: a price
    :param quantity: a quantity
    :param description: a description of the product

    :returns: offer (etree.Element)

    """
    offer = etree.Element('offer')
    offer_reference = offer_data['offer_reference']
    etree.SubElement(offer, "offer_reference", type="SellerSku").text = etree.CDATA(offer_reference)
    offer_data_items = [(k, v) for k, v in offer_data.items() if k != 'offer_reference']

    for key, value in offer_data_items:
        if key == 'product_reference':
            etree.SubElement(offer, 'product_reference', type="Ean").text = str(value)
        elif key == 'description':
            etree.SubElement(offer, 'description').text = etree.CDATA(value)
        else:
            etree.SubElement(offer, key).text = str(value)
    return offer
项目:fnapy    作者:alexandriagroup    | 项目源码 | 文件源码
def delete_offers(self, offer_references):
        """Delete the offers with the given offer_references (sku)

        Usage::

            response = manager.delete_offers(offer_references)

        :param offer_references: the list of SKUs corresponding to the offers
            you want to delete from your catalog

        :returns: :class:`Response <Response>` object

        """
        offers_update = create_xml_element(self.connection, self.token,
                                           'offers_update')
        for offer_reference in offer_references:
            offer = etree.Element('offer')
            etree.SubElement(offer, "offer_reference",
                             type="SellerSku").text = etree.CDATA(offer_reference)
            etree.SubElement(offer, 'treatment').text = 'delete'
            offers_update.append(offer)

        self.offers_update_request = Request(etree.tostring(offers_update,
                                                            **XML_OPTIONS))

        # the response contains the element batch_id
        response = self._get_response(offers_update,
                                      self.offers_update_request.xml)
        self.batch_id = response.dict['offers_update_response']['batch_id']
        return response

    # TODO Create a dictionary for the product_state
项目:fnapy    作者:alexandriagroup    | 项目源码 | 文件源码
def query_carriers(self):
        """Return the available carriers managed on FNAC Marketplace platform

        Usage::

            response = manager.query_carriers()

        :returns: :class:`Response <Response>` object

        """
        carriers_query = create_xml_element(self.connection, self.token, 'carriers_query')
        etree.SubElement(carriers_query, "query").text = etree.CDATA("all")
        self.carriers_query_request = Request(etree.tostring(carriers_query, **XML_OPTIONS))
        return self._get_response(carriers_query, self.carriers_query_request.xml)
项目:fnapy    作者:alexandriagroup    | 项目源码 | 文件源码
def update_client_order_comments(self, seller_comment, order_fnac_id):
        """Reply to client order comments

        Usage::

            response = manager.update_client_order_comments(seller_comment,
                                                            order_fnac_id)

        :type seller_comment: str
        :param seller_comment: The seller comment

        :type order_fnac_id: str
        :param order_fnac_id: Order unique identifier filter from FNAC

        :returns: :class:`Response <Response>` object

        """
        client_order_comments_update = create_xml_element(self.connection, self.token,
                                                          'client_order_comments_update')
        comment = etree.Element('comment', id=order_fnac_id)
        etree.SubElement(comment, 'comment_reply').text = etree.CDATA(seller_comment)
        client_order_comments_update.append(comment)
        self.client_order_comments_update_request = \
            Request(etree.tostring(client_order_comments_update, **XML_OPTIONS))
        return self._get_response(client_order_comments_update,
                                  self.client_order_comments_update_request.xml)
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:Taigabot    作者:FrozenPigs    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:Tencent_Cartoon_Download    作者:Fretice    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:Alexa-Chatter    作者:ekt1701    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:alfred-workflow-snumenu    作者:sungminoh    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:alfredToday    作者:jeeftor    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:EmojiTaco    作者:jeeftor    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:lambda-podcast    作者:marekq    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:lambda-lxml-base    作者:cjpetrus    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap
项目:Stephanie-AI    作者:Elvargy    | 项目源码 | 文件源码
def __init__(self, typemap=None,
                 namespace=None, nsmap=None, makeelement=None):
        if namespace is not None:
            self._namespace = '{' + namespace + '}'
        else:
            self._namespace = None

        if nsmap:
            self._nsmap = dict(nsmap)
        else:
            self._nsmap = None

        if makeelement is not None:
            assert callable(makeelement)
            self._makeelement = makeelement
        else:
            self._makeelement = ET.Element

        # initialize type map for this element factory

        if typemap:
            typemap = typemap.copy()
        else:
            typemap = {}

        def add_text(elem, item):
            try:
                elem[-1].tail = (elem[-1].tail or "") + item
            except IndexError:
                elem.text = (elem.text or "") + item

        def add_cdata(elem, cdata):
            if elem.text:
                raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
            elem.text = cdata

        if str not in typemap:
            typemap[str] = add_text
        if unicode not in typemap:
            typemap[unicode] = add_text
        if ET.CDATA not in typemap:
            typemap[ET.CDATA] = add_cdata

        def add_dict(elem, item):
            attrib = elem.attrib
            for k, v in item.items():
                if isinstance(v, basestring):
                    attrib[k] = v
                else:
                    attrib[k] = typemap[type(v)](None, v)
        if dict not in typemap:
            typemap[dict] = add_dict

        self._typemap = typemap