當前位置: 首頁>>代碼示例>>Python>>正文


Python etree.iselement方法代碼示例

本文整理匯總了Python中lxml.etree.iselement方法的典型用法代碼示例。如果您正苦於以下問題:Python etree.iselement方法的具體用法?Python etree.iselement怎麽用?Python etree.iselement使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在lxml.etree的用法示例。


在下文中一共展示了etree.iselement方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: pretty_print

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def pretty_print(xml):
    """Prints beautiful XML-Code

    This function gets a string containing the xml, an object of
    List[lxml.etree.Element] or directly a lxml element.

    Print it with good readable format.

    Arguments:
        xml (str, List[lxml.etree.Element] or lxml.etree.Element):
            xml as string,
            List[lxml.etree.Element] or directly a lxml element.

    """
    if isinstance(xml, list):
        for item in xml:
            if etree.iselement(item):
                print(etree.tostring(item, pretty_print=True).decode("utf-8"))
            else:
                print(item)
    elif etree.iselement(xml):
        print(etree.tostring(xml, pretty_print=True).decode("utf-8"))
    elif isinstance(xml, str):
        tree = secET.fromstring(xml)
        print(etree.tostring(tree, pretty_print=True).decode("utf-8")) 
開發者ID:greenbone,項目名稱:python-gvm,代碼行數:27,代碼來源:xml.py

示例2: set_trees

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def set_trees(self, left, right):
        self.clear()

        # Make sure we were passed two lxml elements:
        if isinstance(left, etree._ElementTree):
            left = left.getroot()
        if isinstance(right, etree._ElementTree):
            right = right.getroot()

        if not (etree.iselement(left) and etree.iselement(right)):
            raise TypeError("The 'left' and 'right' parameters must be "
                            "lxml Elements.")

        # Left gets modified as a part of the diff, deepcopy it first.
        self.left = deepcopy(left)
        self.right = right 
開發者ID:Shoobx,項目名稱:xmldiff,代碼行數:18,代碼來源:diff.py

示例3: tokenize

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def tokenize(html, include_hrefs=True):
    """
    Parse the given HTML and returns token objects (words with attached tags).

    This parses only the content of a page; anything in the head is
    ignored, and the <head> and <body> elements are themselves
    optional.  The content is then parsed by lxml, which ensures the
    validity of the resulting parsed document (though lxml may make
    incorrect guesses when the markup is particular bad).

    <ins> and <del> tags are also eliminated from the document, as
    that gets confusing.

    If include_hrefs is true, then the href attribute of <a> tags is
    included as a special kind of diffable token."""
    if etree.iselement(html):
        body_el = html
    else:
        body_el = parse_html(html, cleanup=True)
    # Then we split the document into text chunks for each tag, word, and end tag:
    chunks = flatten_el(body_el, skip_tag=True, include_hrefs=include_hrefs)
    # Finally re-joining them into token objects:
    return fixup_chunks(chunks) 
開發者ID:JFox,項目名稱:aws-lambda-lxml,代碼行數:25,代碼來源:diff.py

示例4: handleElement

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def handleElement(self, node, parent):
        """
        Handle an XML element, children and attributes. Returns an XmlElement object.
        """
        if parent is None:
            return None
        # Element
        element = etree.Element("XmlElement")
        ns, tag = split_ns(node.tag)
        element.set("elementName", tag)
        if ns is not None:
            element.set("ns", ns)
        parent.append(element)
        # Element attributes
        for attrib in node.keys():
            attribElement = self.handleAttribute(attrib, node.get(attrib), element)
            element.append(attribElement)
        # Element children
        self._handleText(node.text, element)
        for child in node.iterchildren():
            if etree.iselement(child):  # TODO: skip comments
                self.handleElement(child, element)
            self._handleText(child.tail, element)
        return element 
開發者ID:MozillaSecurity,項目名稱:peach,代碼行數:26,代碼來源:xml.py

示例5: _send_request

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def _send_request(self, request):
        """Send XML data to OpenVAS Manager and get results"""

        block_size = 1024

        if etree.iselement(request):
            root = etree.ElementTree(request)
            root.write(self.socket, encoding="utf-8")

        else:
            if isinstance(request, six.text_type):
                request = request.encode("utf-8")
            self.socket.send(request)

        parser = etree.XMLTreeBuilder()

        while True:
            response = self.socket.recv(block_size)
            parser.feed(response)
            if len(response) < block_size:
                break

        root = parser.close()
        return root 
開發者ID:mpicard,項目名稱:pyvas,代碼行數:26,代碼來源:client.py

示例6: SetXmlBlob

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def SetXmlBlob(self, blob):
        """Sets the contents of the extendedProperty to XML as a child node.

        Since the extendedProperty is only allowed one child element as an XML
        blob, setting the XML blob will erase any preexisting extension elements
        in this object.

        Args:
          blob: str, ElementTree Element or atom.ExtensionElement representing
                the XML blob stored in the extendedProperty.
        """
        # Erase any existing extension_elements, clears the child nodes from the
        # extendedProperty.
        self.extension_elements = []
        if isinstance(blob, atom.ExtensionElement):
            self.extension_elements.append(blob)
        elif ElementTree.iselement(blob):
            self.extension_elements.append(atom._ExtensionElementFromElementTree(
                blob))
        else:
            self.extension_elements.append(atom.ExtensionElementFromString(blob)) 
開發者ID:dvska,項目名稱:gdata-python3,代碼行數:23,代碼來源:__init__.py

示例7: __SendDataPart

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def __SendDataPart(data, connection):
    """This method is deprecated, use atom.http._send_data_part"""
    deprecated('call to deprecated function __SendDataPart')
    if isinstance(data, str):
        # TODO add handling for unicode.
        connection.send(data)
        return
    elif ElementTree.iselement(data):
        connection.send(ElementTree.tostring(data))
        return
    # Check to see if data is a file-like object that has a read method.
    elif hasattr(data, 'read'):
        # Read the file and send it a chunk at a time.
        while 1:
            binarydata = data.read(100000)
            if binarydata == '': break
            connection.send(binarydata)
        return
    else:
        # The data object was not a file.
        # Try to convert to a string and send the data.
        connection.send(str(data))
        return 
開發者ID:dvska,項目名稱:gdata-python3,代碼行數:25,代碼來源:service.py

示例8: CalculateDataLength

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def CalculateDataLength(data):
    """Attempts to determine the length of the data to send.

    This method will respond with a length only if the data is a string or
    and ElementTree element.

    Args:
      data: object If this is not a string or ElementTree element this funtion
          will return None.
    """
    if isinstance(data, str):
        return len(data)
    elif isinstance(data, list):
        return None
    elif ElementTree.iselement(data):
        return len(ElementTree.tostring(data))
    elif hasattr(data, 'read'):
        # If this is a file-like object, don't try to guess the length.
        return None
    else:
        return len(str(data)) 
開發者ID:dvska,項目名稱:gdata-python3,代碼行數:23,代碼來源:service.py

示例9: test_success_response

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def test_success_response(self):
        transform = EtreeCheckCommandTransform()

        root = etree.Element('foo_response')
        root.set('status', '200')

        response = etree.tostring(root).decode('utf-8')

        result = transform(response)

        self.assertTrue(etree.iselement(result))
        self.assertEqual(result.tag, 'foo_response')
        self.assertEqual(result.get('status'), '200') 
開發者ID:greenbone,項目名稱:python-gvm,代碼行數:15,代碼來源:test_etree_check_command_transform.py

示例10: test_transform_response

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def test_transform_response(self):
        transform = EtreeTransform()
        result = transform('<foo/')

        self.assertTrue(etree.iselement(result)) 
開發者ID:greenbone,項目名稱:python-gvm,代碼行數:7,代碼來源:test_etree_transform.py

示例11: test_transform_more_complex_response

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def test_transform_more_complex_response(self):
        transform = EtreeTransform()
        result = transform('<foo id="bar"><lorem/><ipsum/></foo>')

        self.assertTrue(etree.iselement(result))
        self.assertEqual(result.tag, 'foo')
        self.assertEqual(result.get('id'), 'bar')
        self.assertEqual(len(result), 2) 
開發者ID:greenbone,項目名稱:python-gvm,代碼行數:10,代碼來源:test_etree_transform.py

示例12: __call__

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def __call__(self, tag, *children, **attrib):
        get = self._typemap.get

        if self._namespace is not None and tag[0] != '{':
            tag = self._namespace + tag
        elem = self._makeelement(tag, nsmap=self._nsmap)
        if attrib:
            get(dict)(elem, attrib)

        for item in children:
            if callable(item):
                item = item()
            t = get(type(item))
            if t is None:
                if ET.iselement(item):
                    elem.append(item)
                    continue
                for basetype in type(item).__mro__:
                    # See if the typemap knows of any of this type's bases.
                    t = get(basetype)
                    if t is not None:
                        break
                else:
                    raise TypeError("bad argument type: %s(%r)" %
                                    (type(item).__name__, item))
            v = t(elem, item)
            if v:
                get(type(v))(elem, v)

        return elem 
開發者ID:JFox,項目名稱:aws-lambda-lxml,代碼行數:32,代碼來源:builder.py

示例13: __call__

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def __call__(self, tag, *children, **attrib):
        typemap = self._typemap

        if self._namespace is not None and tag[0] != '{':
            tag = self._namespace + tag
        elem = self._makeelement(tag, nsmap=self._nsmap)
        if attrib:
            typemap[dict](elem, attrib)

        for item in children:
            if callable(item):
                item = item()
            t = typemap.get(type(item))
            if t is None:
                if ET.iselement(item):
                    elem.append(item)
                    continue
                for basetype in type(item).__mro__:
                    # See if the typemap knows of any of this type's bases.
                    t = typemap.get(basetype)
                    if t is not None:
                        break
                else:
                    raise TypeError("bad argument type: %s(%r)" %
                                    (type(item).__name__, item))
            v = t(elem, item)
            if v:
                typemap.get(type(v))(elem, v)

        return elem 
開發者ID:wistbean,項目名稱:learn_python3_spider,代碼行數:32,代碼來源:builder.py

示例14: StripComments

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def StripComments(self, node):
        i = 0
        while i < len(node):
            if not etree.iselement(node[i]):
                del node[i] # may not preserve text, don't care
            else:
                self.StripComments(node[i])
                i += 1 
開發者ID:MozillaSecurity,項目名稱:peach,代碼行數:10,代碼來源:parser.py

示例15: test_response_init

# 需要導入模塊: from lxml import etree [as 別名]
# 或者: from lxml.etree import iselement [as 別名]
def test_response_init(response):
    # attributes
    assert response.ok
    assert response.status_code is 200
    assert response.command == "test"
    assert iselement(response.xml)
    # data dict elements
    assert response["@test_id"] == "1234"
    assert response["child"]["@id"] == "1234" 
開發者ID:mpicard,項目名稱:pyvas,代碼行數:11,代碼來源:test_response.py


注:本文中的lxml.etree.iselement方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。