本文整理汇总了Python中lxml.etree.CDATA属性的典型用法代码示例。如果您正苦于以下问题:Python etree.CDATA属性的具体用法?Python etree.CDATA怎么用?Python etree.CDATA使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类lxml.etree
的用法示例。
在下文中一共展示了etree.CDATA属性的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: buildXMLNodes
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def buildXMLNodes(self, element, node):
if type(node) is str or type(node) is int or type(node) is bool:
node = str(node)
element.text = XML.CDATA(node)
else:
for k, v in node.iteritems():
if type(v) is dict:
# serialize the child dictionary
child = XML.Element(k)
self.buildXMLNodes(child, v)
element.append(child)
elif type(v) is list:
if k[-1] == 's':
name = k[:-1]
else:
name = k
for item in v:
child = XML.Element(name)
self.buildXMLNodes(child, item)
element.append(child)
else:
# add attributes to the current element
element.set(k, unicode(v))
示例2: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def __init__(self, tag, adapter, ns=const.UOM_NS, attrib=None, text='',
children=(), cdata=False):
# Defaults shouldn't be mutable
attrib = attrib if attrib else {}
self.element = None
if ns:
self.element = etree.Element(str(etree.QName(ns, tag)),
attrib=attrib)
else:
self.element = etree.Element(tag, attrib=attrib)
if text:
self.element.text = etree.CDATA(text) if cdata else text
for c in children:
# Use a deep copy, else, c.element gets *removed* from its parent
# hierarchy (see fourth bullet: http://lxml.de/compatibility.html).
# Doing the deepcopy here means the caller doesn't have to worry
# about it.
self.element.append(copy.deepcopy(c.element))
self.adapter = adapter
示例3: insert_cdata
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def insert_cdata(self, index, tag, attrib, cdata_text):
"""
Insert cdata in the SVG
:param index:
:type index: int
:param tag:
:type tag:
:param attrib:
:type attrib: dict
:param cdata_text:
:type cdata_text: str
:return:
:rtype:
"""
element = etree.Element(tag, attrib=attrib)
element.text = etree.CDATA(cdata_text)
self.root.insert(index, element)
示例4: GetAttributeValue
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
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 text(unescape(attr.childNodes[0].data))
else:
# content is a CDATA
txt = u''
for node in attr.childNodes:
if not (node.nodeName == "#text" and node.data.strip() == u''):
txt += text(unescape(node.data))
return text
示例5: render_testcase_failures
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def render_testcase_failures(self, testcase_report):
"""
Entries of a testcase report are in dict form, which may
also be nested in case there are groups/summaries.
This method flattens the enty data and iterates over failing
assertions to create `failure` tags with element tree.
"""
# Depth does not matter, we just need entries in flat form
flat_dicts = list(zip(*testcase_report.flattened_entries(depth=0)))[1]
failed_assertions = [
entry
for entry in flat_dicts
# Only get failing assertions
if entry["meta_type"] == "assertion" and not entry["passed"] and
# Groups have no use in XML output
not entry["type"] in ("Group", "Summary")
]
failures = []
for entry in failed_assertions:
failure = E.failure(
message=entry["description"] or entry["type"], type="assertion"
)
if entry["type"] == "RawAssertion":
failure.text = etree.CDATA(entry["content"])
failures.append(failure)
return failures
示例6: add_text_argument
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
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
示例7: cdata_tags
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def cdata_tags(elem, tags):
""" Expand text to CDATA, if it isn't already. """
cache = FileReadlinesCache()
CDATA = "<![CDATA["
def already_using_cdata(elem):
# WARNING: Super wonky hack! I can't find any programmatic way to determine if .text
# (or some part of it) contains CDATA. There seems to be some hidden magic here,
# in how this is implemented. Patches welcome!
# HACK optimization: Cache the contents of the file to prevent dozens of re-reads
lines = cache.readlines(elem.base)
lineno = elem.sourceline - 1
source_lines = lines[lineno:lineno + 2]
for line in source_lines:
if CDATA in line:
#print("Found source line: {}".format(line))
return True
return False
for tag in tags:
for e in elem.findall(".//{}".format(tag)):
if e.text and e.text.strip():
# Determine if the data is ALREADY in a CDATA element
# if isinstance(e.text, etree.CDATA): # Doesn't work...
if already_using_cdata(e):
pass
elif re.search(r'[<>&]', e.text):
#print("SHOULD BE CDATA: {}".format(e.text))
# Convert text to CDATA
e.text = etree.CDATA(e.text)
示例8: GenerateAnyInfos
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
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, (string_types, etree.ElementBase))
}
示例9: gen_ncclient_script
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def gen_ncclient_script(username, payload):
"""
Generate Netconf / Restconf RPC
"""
payload = payload.replace('<metadata>', '')
payload = payload.replace('</metadata>', '')
_, device, fmt, lock, rpc = Adapter.parse_request(payload)
if fmt == 'xpath' and rpc == '':
rpc = Adapter.gen_rpc(username, payload)
if rpc is None:
logging.error('gen_script: Invalid RPC Generated')
return None
parser = NetconfParser(rpc)
op = parser.get_operation()
data = ET.tostring(parser.get_data(), pretty_print=True)
datastore = parser.get_datastore()
# setup template args
args = dict()
args['data'] = data.strip()
args['datastore'] = datastore
args['host'] = device.get('host', '')
args['port'] = device.get('port', '830')
args['user'] = device.get('user', '')
args['passwd'] = device.get('passwd', '')
args['platform'] = device.get('platform', '')
if not args['host']:
args['host'] = '<address>'
if not args['user']:
args['user'] = '<username>'
if not args['passwd']:
args['passwd'] = '<password>'
if not args['platform']:
args['platform'] = 'csr'
if op == 'get':
args['nccall'] = 'm.get(payload).xml'
elif op == 'get-config':
args['nccall'] = "m.get_config(source='%s', filter=payload).xml" % datastore
elif op == 'edit-config':
e_opt = parser.get_error_option()
if e_opt is None or e_opt == '':
args['nccall'] = "m.edit_config(target='%s', config=payload).xml" % datastore
else:
args['nccall'] = "m.edit_config(target='%s', error_option='%s', config=payload).xml" % (datastore, e_opt)
args['lock'] = lock
else:
args['nccall'] = "m.dispatch(ET.fromstring(payload)).xml"
# generate script
rendered = render_to_string('pyscript.py', args)
script = ET.Element('script')
script.text = ET.CDATA(rendered)
return script
示例10: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
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
示例11: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
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 = dict(typemap)
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
示例12: __process_xml
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import CDATA [as 别名]
def __process_xml (self, filename):
if filename is None:
return
print "\nSaving XML file: " + filename
root = etree.Element(u"theHarvester")
emails_elem = etree.SubElement(root, u"emails")
for x in self.output_results.emails:
email_elem = etree.SubElement(emails_elem, u"email")
email_elem.text = x
hosts_elem = etree.SubElement(root, u"hosts")
for host, ip in self.output_results.search_hosts_ips.iteritems() :
self.__add_host (hosts_elem, host, ip)
people_elem = etree.SubElement(root, u"people")
for x in self.output_results.people:
person_elem = etree.SubElement(people_elem, u"person")
person_elem.text = x
vhosts_elem = etree.SubElement(root, u"vhosts")
for host, ip in self.output_results.virtual_host_results.iteritems() :
self.__add_host (vhosts_elem, host, ip)
dns_brute_elem = etree.SubElement(root, u"dns_brute_hosts")
for host, ip in self.output_results.dns_brute_results.iteritems() :
self.__add_host (dns_brute_elem, host, ip)
dns_tld_elem = etree.SubElement(root, u"dns_tld_hosts")
for host, ip in self.output_results.dns_tld_results.iteritems() :
self.__add_host (dns_tld_elem, host, ip)
dns_reverse_elem = etree.SubElement(root, u"dns_reverse_hosts")
for host, ip in self.output_results.dns_reverse_results.iteritems() :
self.__add_host (dns_reverse_elem, host, ip)
dns_shodan_elem = etree.SubElement(root, u"shodan")
for shodan_result in self.output_results.shodan_results:
host_elem = etree.SubElement(dns_shodan_elem, u"host")
name_elem = etree.SubElement(host_elem, u"name")
name_elem.text = shodan_result.host
ip_elem = etree.SubElement(host_elem, u"ip")
ip_elem.text = shodan_result.ip
port_elem = etree.SubElement(host_elem, u"port")
port_elem.text = shodan_result.port
banner_elem = etree.SubElement(host_elem, u"banner")
banner_elem.text = etree.CDATA(shodan_result.banner)
last_update_elem = etree.SubElement(host_elem, u"last_update")
last_update_elem.text = shodan_result.last_update
with open(filename,'w') as file:
try:
file.write(etree.tostring(root, pretty_print=True))
except Exception as e:
print e
print "Error creating the XML file"