本文整理汇总了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"))
示例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
示例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)
示例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
示例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
示例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))
示例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
示例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))
示例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')
示例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))
示例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)
示例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
示例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
示例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
示例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"