本文整理汇总了Python中lxml.etree.SubElement方法的典型用法代码示例。如果您正苦于以下问题:Python etree.SubElement方法的具体用法?Python etree.SubElement怎么用?Python etree.SubElement使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree
的用法示例。
在下文中一共展示了etree.SubElement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_package_container
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def create_package_container(self, project, package, meta=None, disable_build=False):
"""
Creates a package container without any fields in project/package
:param project: project to create it
:param package: package name
:param meta: package metadata
:param disable_build: should the package be created with build
flag disabled
"""
if not meta:
meta = '<package name="{}"><title/><description/></package>'
meta = meta.format(package)
if disable_build:
root = ET.fromstring(meta)
elm = ET.SubElement(root, 'build')
ET.SubElement(elm, 'disable')
meta = ET.tostring(root)
url = self.makeurl(['source', project, package, '_meta'])
http_PUT(url, data=meta)
示例2: ensure_staging_archs
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def ensure_staging_archs(self, project):
meta = ET.parse(http_GET(self.project_meta_url(project)))
repository = meta.find('repository[@name="{}"]'.format(self.cmain_repo))
changed = False
for arch in self.cstaging_archs:
if not repository.xpath('./arch[text()="{}"]'.format(arch)):
elm = ET.SubElement(repository, 'arch')
elm.text = arch
changed = True
if not changed:
return
meta = ET.tostring(meta)
http_PUT(self.project_meta_url(project), data=meta)
示例3: add_bugowner
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def add_bugowner(self, package, owner):
url = self.makeurl(['source', self.project, package, '_meta'])
root = ET.fromstring(self.cached_GET(url))
idname = 'userid' if owner.kind == 'person' else 'groupid'
# XXX: can't use 'and' here to filter for bugowner too
exists = root.findall('./{}[@{}="{}"]'.format(owner.kind, idname, owner.name))
for node in exists:
if node.get('role') == 'bugowner':
logger.debug("%s/%s already has %s %s", self.project, package, owner.kind, owner.name)
return
node = ET.SubElement(root, owner.kind)
node.set(idname, owner.name)
node.set('role', 'bugowner')
data = ET.tostring(root)
logger.debug(data)
self.http_PUT(url, data=data)
示例4: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def __init__(self, name, project, devel_project=None):
self.name = name
self.project = project
meta = """
<package project="{1}" name="{0}">
<title></title>
<description></description>
</package>""".format(self.name, self.project.name)
if devel_project:
root = ET.fromstring(meta)
ET.SubElement(root, 'devel', { 'project': devel_project })
meta = ET.tostring(root)
url = osc.core.make_meta_url('pkg', (self.project.name, self.name), APIURL)
osc.core.http_PUT(url, data=meta)
print('created {}/{}'.format(self.project.name, self.name))
self.project.add_package(self)
# delete from instance
示例5: _render_data
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def _render_data(el, data):
if isinstance(data, list):
for item in data:
sub_el = etree.SubElement(el, 'item')
_render_data(sub_el, item)
elif isinstance(data, dict):
_render_dict(el, data)
elif hasattr(data, '__dict__'):
_render_dict(el, data.__dict__)
elif isinstance(data, bool):
el.text = str(data).lower()
elif isinstance(data, datetime.datetime):
el.text = _database_to_isoformat(data)
elif isinstance(data, six.binary_type):
el.text = data.decode("utf-8")
elif data is not None:
el.text = six.text_type(data)
示例6: import_metadata_from_directory
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def import_metadata_from_directory(self, dir):
# load policies
# print "ppath = ", (path(dir) / 'policies/*')
for pdir in glob.glob(path(dir) / 'policies/*'):
# print "pdir=",pdir
policies = etree.Element('policies')
policies.set('semester',os.path.basename(pdir))
for fn in glob.glob(path(pdir) / '*.json'):
x = etree.SubElement(policies,os.path.basename(fn).replace('_','').replace('.json',''))
x.text = open(fn).read()
self.add_policies(policies)
# load about files
for afn in glob.glob(dir / 'about/*'):
try:
self.add_about_file(os.path.basename(afn), open(afn).read())
except Exception as err:
print "Oops, failed to add file %s, error=%s" % (afn, err)
示例7: mapSave
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def mapSave(regions,filename):
"""
Saves a region map to an XML file
"""
root = ET.Element('map')
for name,table in regions.items():
node = ET.SubElement(root,'region')
node.set('name',name)
if table.has_key('value'): node.set('value',str(table['value']))
if table.has_key('occupants'): node.set('occupants',str(table['occupants']))
node.set('owner',str(table['owner']))
for neighbor in table['neighbors']:
subnode = ET.SubElement(node,'neighbor')
subnode.set('name',neighbor)
tree = ET.ElementTree(root)
tree.write(filename,pretty_print=True)
return tree
示例8: output2lex
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def output2lex(output,filename):
lexicon_output = open(filename,"wb")
lexicon = ET.Element("lexicon")
tree = ET.ElementTree(lexicon)
for list_item in output:
lex_entry = ET.SubElement(lexicon,"lex")
if list_item["pron"] is not None:
lex_entry.attrib["ipa"]=list_item["pron"]
if list_item["x-sampa"] is not None:
lex_entry.attrib["x-sampa"]=list_item["x-sampa"]
lex_entry.text=list_item["word"]
tree.write(
lexicon_output,pretty_print=True,
xml_declaration=True,encoding="utf-8")
示例9: create_output
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def create_output(phone_map,output_file,nuclei=[],add_nuclei=False):
root = ET.Element("ipa_mapping")
tree = ET.ElementTree(root)
for ipa, phone in phone_map.items():
mapping = ET.SubElement(root, "map")
mapping.attrib["pron"] = phone
mapping.attrib["ipa"] = ipa
if add_nuclei:
if phone in nuclei:
mapping.attrib["nucleus"] = "true"
else:
mapping.attrib["nucleus"] = "false"
mapping_output = open(output_file,"wb")
tree.write(
mapping_output,pretty_print=True,
xml_declaration=True,encoding="utf-8")
示例10: store_text
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def store_text(self, sentence, sample, output_dir, extension):
ns = sample['ns']
line = sample['xml_element']
textequivxml = line.find('./ns:TextEquiv[@index="{}"]'.format(self.text_index),
namespaces=ns)
if textequivxml is None:
textequivxml = etree.SubElement(line, "TextEquiv", attrib={"index": str(self.text_index)})
u_xml = textequivxml.find('./ns:Unicode', namespaces=ns)
if u_xml is None:
u_xml = etree.SubElement(textequivxml, "Unicode")
u_xml.text = sentence
# check if page can be stored, this requires that (standard in prediction) the pages are passed sequentially
if self._last_page_id != sample['page_id']:
if self._last_page_id:
self._store_page(extension, self._last_page_id)
self._last_page_id = sample['page_id']
示例11: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def __init__(self, command): # type: (str) -> None
self.envelope = None
self.command = command
self.request = None
self.updates = None
self.batch = None
# HEADER GLOBALS
SOAPENV_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"
SOAPENV = "{%s}" % SOAPENV_NAMESPACE
ns0_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"
ns1_NAMESPACE = "http://schemas.microsoft.com/sharepoint/soap/"
xsi_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"
NSMAP = {"SOAP-ENV": SOAPENV_NAMESPACE, "ns0": ns0_NAMESPACE, "ns1": ns1_NAMESPACE, "xsi": xsi_NAMESPACE}
# Create Header
self.envelope = etree.Element(SOAPENV + "Envelope", nsmap=NSMAP)
HEADER = etree.SubElement(self.envelope, "{http://schemas.xmlsoap.org/soap/envelope/}Body")
# Create Command
self.command = etree.SubElement(HEADER, "{http://schemas.microsoft.com/sharepoint/soap/}" + command)
self.start_str = b"""<?xml version="1.0" encoding="utf-8"?>"""
示例12: add_query
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def add_query(self, pyquery):
# type: (Dict) -> None
query = etree.SubElement(self.command, "{http://schemas.microsoft.com/sharepoint/soap/}query")
Query = etree.SubElement(query, "Query")
if "OrderBy" in pyquery:
order = etree.SubElement(Query, "OrderBy")
for field in pyquery["OrderBy"]:
fieldref = etree.SubElement(order, "FieldRef")
if type(field) == tuple:
fieldref.set("Name", field[0])
if field[1] == "DESCENDING":
fieldref.set("Ascending", "FALSE")
else:
fieldref.set("Name", field)
if "GroupBy" in pyquery:
order = etree.SubElement(Query, "GroupBy")
for field in pyquery["GroupBy"]:
fieldref = etree.SubElement(order, "FieldRef")
fieldref.set("Name", field)
if "Where" in pyquery:
Query.append(pyquery["Where"])
示例13: parse_dict
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def parse_dict(xml_root_object, dict_to_parse):
for subitem in dict_to_parse.items():
# subitem is now a tuple of key, value in the dict
xml_subitem_name = subitem[0]
if type(subitem[1]) in (str, int, None):
if subitem[0][0] == '@':
xml_root_object.set(subitem[0][1:], str(subitem[1]))
else:
xml_subitem = et.SubElement(xml_root_object, xml_subitem_name)
xml_subitem.text = str(subitem[1])
elif type(subitem[1]) is dict:
xml_subitem = et.SubElement(xml_root_object, xml_subitem_name)
parse_dict(xml_subitem, subitem[1])
elif type(subitem[1]) is list:
for item in subitem[1]:
if type(item) is dict:
xml_subitem = et.SubElement(xml_root_object, xml_subitem_name)
parse_dict(xml_subitem, item)
elif type(item) is str:
xml_subitem = et.SubElement(xml_root_object, xml_subitem_name)
xml_subitem.text = str(item)
示例14: add_xml_class
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def add_xml_class(self, package, smali_class):
class_insns_covered = 0
class_insns_missed = 0
xml_class = SubElement(package, "class")
xml_class.set("name", smali_class.name[1:-1])
class_instructions_added = 0
for m in smali_class.methods:
if (m.cover_code > -1): # not abstract and not native method
xml_method = self.create_xml_method(xml_class, m)
if Granularity.is_instruction(self.granularity):
lines_covered = m.covered()
lines_missed = m.not_covered()
self.add_xml_insn_counter(xml_method, lines_covered, lines_missed, "INSTRUCTION")
class_insns_covered += lines_covered
class_insns_missed += lines_missed
class_instructions_added += 1
if Granularity.is_method(self.granularity):
self.add_xml_insn_counter(xml_method, int(m.called), 1-int(m.called), "METHOD")
methods_covered = smali_class.mtds_covered()
methods_missed = smali_class.mtds_coverable() - methods_covered
if class_instructions_added:
self.add_xml_insn_counter(xml_class, class_insns_covered, class_insns_missed, "INSTRUCTION")
self.add_xml_insn_counter(xml_class, methods_covered, methods_missed, "METHOD")
示例15: keypoints2xml_object
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import SubElement [as 别名]
def keypoints2xml_object(anno, xmltree, keypoints_dict, bbox_type='xyxy'):
assert bbox_type in ['xyxy', 'xywh']
if bbox_type == 'xyxy':
xmin, ymin, w, h = anno['bbox']
xmax = xmin+w
ymax = ymin+h
else:
xmin, ymin, xmax, ymax = anno['bbox']
key_object = etree.SubElement(xmltree, "object")
etree.SubElement(key_object, "name").text = anno['category_id']
bndbox = etree.SubElement(key_object, "bndbox")
etree.SubElement(bndbox, "xmin").text = str(xmin)
etree.SubElement(bndbox, "ymin").text = str(ymin)
etree.SubElement(bndbox, "xmax").text = str(xmax)
etree.SubElement(bndbox, "ymax").text = str(ymax)
etree.SubElement(key_object, "difficult").text = '0'
keypoints = etree.SubElement(key_object, "keypoints")
for i in range(0, len(keypoints_dict)):
keypoint = etree.SubElement(keypoints, keypoints_dict[i+1])
etree.SubElement(keypoint, "x").text = str(anno['keypoints'][i*3])
etree.SubElement(keypoint, "y").text = str(anno['keypoints'][i*3+1])
etree.SubElement(keypoint, "v").text = str(anno['keypoints'][i*3+2])
return xmltree