本文整理汇总了Python中xml.etree.ElementTree.SubElement.attrib方法的典型用法代码示例。如果您正苦于以下问题:Python SubElement.attrib方法的具体用法?Python SubElement.attrib怎么用?Python SubElement.attrib使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.SubElement
的用法示例。
在下文中一共展示了SubElement.attrib方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: data2xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def data2xml(self,datas):
self.savedata=datas
fps=Element('fps')
fps.attrib={'verdion':'1.2'}
self.now._setroot(fps)
item=SubElement(fps,'item')
SubElement(item,'title').text=datas['title']
time_limit=SubElement(item,'time_limit')
time_limit.attrib={'unit':'s'}
time_limit.text='1'
memory_limit=SubElement(item,'memory_limit')
memory_limit.attrib={'unit':'mb'}
memory_limit.text='64'
all=datas['src_num']
print 'all of image :',all
i=0
print datas
while i!=all:
img=SubElement(item,'img')
src=SubElement(img,'src')
src.text=datas['src'][i]
base64=SubElement(img,'base64')
base64.text=datas['base64'][i]
i=i+1
SubElement(item,'description').text=datas['description']
SubElement(item,'input').text=datas['input']
SubElement(item,'output').text=datas['output']
sample_input=SubElement(item,'sample_input')
data=CDATA(datas['sample_input'])
sample_input.append(data)
sample_output=SubElement(item,'sample_output')
data=CDATA(datas['sample_output'])
sample_output.append(data)
test_input=SubElement(item,'test_input')
data=CDATA(datas['sample_input'])
test_input.append(data)
test_output=SubElement(item,'test_output')
data=CDATA(datas['sample_output'])
test_output.append(data)
# SubElement(item,'test_input').append(CDATA(datas['sample_input']))
# SubElement(item,'test_output').append(CDATA(datas['sample_output']))
solution=SubElement(item,'solution')
data=CDATA(datas['solution'])
solution.append(data)
solution.attrib={'language':'C++'}
SubElement(item,'hint').text=datas['hint']
SubElement(item,'source').text=datas['source']+'(POJ'+' '+datas['ID']+')'
# dump(indent(fps))
self.save(datas)
示例2: xmlrpc_playlist
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def xmlrpc_playlist():
db = conn.cursor()
history = [ ]
requests = [ ]
db.execute("SELECT * FROM history ORDER BY id DESC")
rows = db.fetchall()
for row in rows:
i_user = row[2]
history.append(get_song(row[1], i_user=i_user))
# Get the request list
db.execute("SELECT * FROM requests ORDER BY id DESC")
rows = db.fetchall()
for row in rows:
i_user = row[2]
requests.append(get_song(row[0], i_user=i_user))
# Last song in this history list is what's currently playing
playing = history.pop()
# Create the XML
root = Element('playlist')
parent = SubElement(root, "nowplaying")
child = SubElement(parent, "song")
attribs = {'artist': playing['artist'],
'title': playing['title'],
'requestby': playing['username']}
child.attrib = attribs
parent = SubElement(root, "history")
for song in history:
child = SubElement(parent, "song")
attribs = {'artist': song['artist'],
'title': song['title'],
'requestby': song['username']}
child.attrib = attribs
parent = SubElement(root, "upcoming")
for song in requests:
child = SubElement(parent, "song")
attribs = {'artist': song['artist'],
'title': song['title'],
'requestby': song['username']}
child.attrib = attribs
# FIXME: there literally has to be a better way to do this.
return parseString(tostring(root)).toprettyxml()
示例3: mergePopulationData
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def mergePopulationData(populationFile, regionFile, mergedFile):
csvReader = csv.reader(open(populationFile), delimiter=',', quotechar='"')
inhabDict = {}
for entry in csvReader:
if csvReader.line_num <= 3:
continue
while(len(entry[0]) < 2):
entry[0] = '0' + entry[0]
while(len(entry[2]) < 2):
entry[2] = '0' + entry[2]
while(len(entry[3]) < 4):
entry[3] = '0' + entry[3]
while(len(entry[4]) < 3):
entry[4] = '0' + entry[4]
inhabDict["".join(entry[:5])] = str(entry[6]).replace(' ', '')
root = ET.ElementTree(file=regionFile).getroot()
for parents in root.findall("./*"):
for elem in parents.findall("param[7]"):
RSValue = str(elem.attrib)[11:23]
inhabitants = SubElement(parents, 'param')
if RSValue in inhabDict:
inhabitants.clear()
inhabitants.attrib = {
'key': "INHABITANTS", 'value': inhabDict[RSValue]}
outstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open(mergedFile, 'w') as out:
out.write(outstr.encode('utf-8'))
示例4: toxml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def toxml(self, parent):
file = SubElement(parent, 'file')
file.attrib = {'original': self.original, 'source-language': self.source_language, 'datatype': self.data_type,
'target-language': self.target_language}
self.header.toxml(file)
self.body.toxml(file)
return file
示例5: post_entry
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def post_entry(self, title, content, updated=None, draft=False):
if updated and isinstance(updated, datetime) is False:
raise TypeError('Updated is must be datetime type. Passed updated is {}'.format(type(updated)))
entry = Element('entry')
entry.attrib = {'xmlns': 'http://purl.org/atom/ns#'}
_title = SubElement(entry, 'title')
_title.text = title
_content = SubElement(entry, 'content')
_content.attrib = {'type': 'text/plain'}
_content.text = content
_updated = SubElement(entry, 'updated')
if updated:
# default timezone is JST
utc_offset = re.sub(r'((?:\+|-)\d{2})(\d{2})', r'\1:\2', updated.strftime('%z')) if updated.tzinfo else '+09:00'
_updated.text = updated.strftime('%Y-%m-%dT%H:%M:%S{utc_offset}'.format(utc_offset=utc_offset))
else:
_updated.text = None
data = minidom.parseString(ET.tostring(entry)).toxml(encoding='utf-8')
url = self.draft_collection if draft else self.collection_url
response = requests.post(url=url, data=data, auth=self.auth)
if response.ok:
return ET.fromstring(response.text)
else:
return {'status_code': response.status_code, 'reason': response.reason}
示例6: edit_entry
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def edit_entry(self, date, entry_id, title, content, updated=None, draft=False):
entry = Element('entry')
entry.attrib = {'xmlns': 'http://purl.org/atom/ns#'}
_title = SubElement(entry, 'title')
_title.text = title
_content = SubElement(entry, 'content')
_content.attrib = {'type': 'text/plain'}
_content.text = content
_updated = SubElement(entry, 'updated')
_updated.text = updated
data = minidom.parseString(ET.tostring(entry)).toxml(encoding='utf-8')
url = self.draft_member.format(entry_id=entry_id) if draft else self.member_url.format(date=date, entry_id=entry_id)
response = requests.put(url=url, data=data, auth=self.auth)
if response.ok:
return ET.fromstring(response.text)
else:
return {'status_code': response.status_code, 'reason': response.reason}
示例7: _to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def _to_xml(self, parent=None, excludes=[]):
"""
Serialize document to xml
"""
if parent is not None:
root = SubElement(parent, self._tagname)
else:
root = Element(self._tagname)
for name, field in sorted(self._fields.items()):
if name in self.xml_exclude or name in excludes:
continue
value = getattr(self, name)
if value is None:
# skip not filled fields
continue
attribs = dict()
if isinstance(field, IntField) and name is not 'id':
attribs['type'] = 'integer'
if isinstance(field, PyDateTimeField):
attribs['type'] = 'datetime'
value = value.strftime('%Y/%m/%d %H:%M:%S %Z')
if isinstance(field, PyBooleanField):
attribs['type'] = 'boolean'
value = str(value).lower()
if isinstance(field, EmbeddedDocumentField):
value._to_xml(root)
else:
elem = SubElement(root, name)
elem.text = str(value)
elem.attrib = attribs
# allow sub classes to add custom ad-hoc fields
self._contribute_to_xml(root)
return tostring(root)
示例8: _contribute_to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def _contribute_to_xml(self, etree):
if getattr(self, "no_owner", False):
elem = SubElement(etree, "no_owner")
elem.text = str(True).lower()
elem.attrib = {'type': 'boolean'}
示例9: get_vulnerability
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib [as 别名]
def get_vulnerability(filename="", run_time=10):
tree = ET.parse(filename)
root = tree.getroot()
issues = []
preferences = root.findall(
"Policy/Preferences/ServerPreferences/preference")
for preference in preferences:
result = {}
for node in preference:
result[node.tag] = node.text
if result["name"] == "plugin_set":
plugin_set = result["value"]
number_tests = len(plugin_set.split(";"))
severity_match = {0: "S4", 1: "S3", 2: "S2", 3: "S1", 4: "S0"}
testsuites = Element("testsuites")
number_issues = 0
for elem in root.findall("Report/ReportHost"):
# need to get host name or IP address
host = elem.attrib["name"]
testsuite = SubElement(testsuites, "testsuite")
for issue in elem.findall("ReportItem"):
number_issues = number_issues + 1
testcase = SubElement(testsuite, "testcase")
attribs = issue.attrib
failure = SubElement(testcase, "failure")
description = ""
synopsis = ""
plugin_output = ""
see_also = ""
solution = ""
fname = ""
plugin_type = ""
plugin_publication_date = ""
plugin_modification_date = ""
plugin_name = ""
fname = ""
script_version = ""
risk_factor = ""
for atom in issue:
if atom.tag == "description":
description = atom.text
elif atom.tag == "synopsis":
synopsis = atom.text
elif atom.tag == "plugin_output":
plugin_output = atom.text
elif atom.tag == "see_also":
see_also = atom.text
elif atom.tag == "solution":
solution = atom.text
elif atom.tag == "fname":
fname = atom.text
elif atom.tag == "plugin_modification_date":
plugin_modification_date = atom.text
elif atom.tag == "plugin_name":
plugin_name = atom.text
elif atom.tag == "plugin_type":
plugin_type = atom.text
elif atom.tag == "risk_factor":
risk_factor = atom.text
elif atom.tag == "script_version":
script_version = atom.text
testcase_attribs = {}
sev_level = int(attribs["severity"])
testcase_attribs["severity"] = severity_match[sev_level]
testcase_attribs["name"] = attribs["pluginName"]
testcase_attribs["pluginID"] = attribs["pluginID"]
testcase_attribs["pluginName"] = attribs["pluginName"]
testcase_attribs["classname"] = attribs["pluginID"]
testcase.attrib = testcase_attribs
failure.text = u"""Host:{}
Description:{}
Severity:{}
Fname:{}
Plugin_modification_date:{}
Plugin_name:{}
Plugin_publication_date:{}
Plugin_type:{}
Risk_factor:{}
Script_version:{}
See Also:{}
Solution:{}
Synopsis:{}
Plugin_output:{}
""".format(
host,
description,
testcase_attribs["severity"],
fname,
plugin_modification_date,
plugin_name,
plugin_publication_date,
plugin_type,
risk_factor,
script_version,
see_also,
solution,
#.........这里部分代码省略.........