本文整理汇总了Python中xml.dom.minidom.Document.createElement方法的典型用法代码示例。如果您正苦于以下问题:Python Document.createElement方法的具体用法?Python Document.createElement怎么用?Python Document.createElement使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.dom.minidom.Document
的用法示例。
在下文中一共展示了Document.createElement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
class Output:
def __init__(self, filename):
self.filename = filename.replace(".", "_") + ".xml"
self.doc = Document()
self.rootNode = self.doc.createElement("package")
self.doc.appendChild(self.rootNode)
def insert(self, label, content = None, parent = None):
item = self.doc.createElement(label)
if content != None:
item_content = self.doc.createTextNode(str(content))
item.appendChild(item_content)
if parent == None:
parent = self.rootNode
parent.appendChild(item)
return item
def get_rootNode(self):
pass
def write(self):
dir_ = "report/"
if not os.path.isdir(dir_):
os.makedirs(dir_)
file = open(dir_ + self.filename, "a")
file.write(self.doc.toprettyxml(indent="\t"))
file.close()
示例2: write_xml_hypergraph
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def write_xml_hypergraph(hypergraph):
"""
Return a string specifying the given hypergraph as a XML document.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph.
@rtype: string
@return: String specifying the graph as a XML document.
"""
# Document root
grxml = Document()
grxmlr = grxml.createElement('hypergraph')
grxml.appendChild(grxmlr)
# Each node...
nodes = hypergraph.nodes()
hyperedges = hypergraph.get_hyperedges()
for each_node in (nodes + hyperedges):
if (each_node in nodes):
node = grxml.createElement('node')
else:
node = grxml.createElement('hyperedge')
node.setAttribute('id',str(each_node))
grxmlr.appendChild(node)
# and its outgoing edge
for each_edge in hypergraph.get_links(each_node):
edge = grxml.createElement('link')
edge.setAttribute('to',str(each_edge))
node.appendChild(edge)
return grxml.toprettyxml()
示例3: CopyBinaries
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def CopyBinaries(out_dir, out_project_dir, src_package, shared):
# Copy jar files to libs.
libs_dir = os.path.join(out_project_dir, 'libs')
if not os.path.exists(libs_dir):
os.mkdir(libs_dir)
if shared:
libs_to_copy = ['xwalk_core_library_java_app_part.jar']
elif src_package:
libs_to_copy = ['jsr_305_javalib.jar', ]
else:
libs_to_copy = ['xwalk_core_library_java.jar', ]
for lib in libs_to_copy:
source_file = os.path.join(out_dir, 'lib.java', lib)
target_file = os.path.join(libs_dir, lib)
shutil.copyfile(source_file, target_file)
if shared:
return
print 'Copying binaries...'
# Copy assets.
res_raw_dir = os.path.join(out_project_dir, 'res', 'raw')
res_value_dir = os.path.join(out_project_dir, 'res', 'values')
if not os.path.exists(res_raw_dir):
os.mkdir(res_raw_dir)
if not os.path.exists(res_value_dir):
os.mkdir(res_value_dir)
paks_to_copy = [
'icudtl.dat',
# Please refer to XWALK-3516, disable v8 use external startup data,
# reopen it if needed later.
# 'natives_blob.bin',
# 'snapshot_blob.bin',
'xwalk.pak',
]
pak_list_xml = Document()
resources_node = pak_list_xml.createElement('resources')
string_array_node = pak_list_xml.createElement('string-array')
string_array_node.setAttribute('name', 'xwalk_resources_list')
pak_list_xml.appendChild(resources_node)
resources_node.appendChild(string_array_node)
for pak in paks_to_copy:
source_file = os.path.join(out_dir, pak)
target_file = os.path.join(res_raw_dir, pak)
shutil.copyfile(source_file, target_file)
item_node = pak_list_xml.createElement('item')
item_node.appendChild(pak_list_xml.createTextNode(pak))
string_array_node.appendChild(item_node)
pak_list_file = open(os.path.join(res_value_dir,
'xwalk_resources_list.xml'), 'w')
pak_list_xml.writexml(pak_list_file, newl='\n', encoding='utf-8')
pak_list_file.close()
# Copy native libraries.
source_dir = os.path.join(out_dir, XWALK_CORE_SHELL_APK, 'libs')
distutils.dir_util.copy_tree(source_dir, libs_dir)
示例4: consoleElement
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def consoleElement(deviceType, port):
"""
Creates a character device element, a <console> element, as a child
of L{device element<devicesElement>}, that specifies the console character
device to be used. Examples from libvirt.org:
Domain Logfile: This disables all input on the character device, and
sends output into the virtual machine's logfile.
- type: stdio
- port: 1
@param deviceType: device type
@type deviceType: String
@param port: port number
@type port: String
@return: <console> element
@rtype: String
"""
document = Document()
deviceElem = document.createElement('console')
deviceElem.setAttribute('type', deviceType)
portElem = document.createElement('target')
portElem.setAttribute('port', port)
deviceElem.appendChild(portElem)
return deviceElem
示例5: questions_to_aiml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def questions_to_aiml(questions):
punctuation = "\"`[email protected]#$%^&()-_=+[{]}\|;:',<.>/?"
_puncStripRE = re.compile("[" + re.escape(punctuation) + "]")
# Create the minidom document
doc = Document()
# Create the <aiml> base element
aiml = doc.createElement("aiml")
doc.appendChild(aiml)
for question, answer in questions:
patterns = (re.sub(_puncStripRE, "", question), re.sub(_puncStripRE, "*", question))
for p in patterns:
category = doc.createElement("category")
pattern = doc.createElement("pattern")
pattern.appendChild(doc.createTextNode(p.upper()))
template = doc.createElement("template")
template.appendChild(doc.createTextNode(answer))
category.appendChild(pattern)
category.appendChild(template)
aiml.appendChild(category)
# Print our newly created XML
return doc.toxml()
示例6: doStartSession
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def doStartSession(self, args={}):
url = self.base_url + "/start.php"
doc = Document()
sessionNode = doc.createElement("session")
sessionNode.setAttribute("mode", "desktop")
userNode = doc.createElement("user")
userNode.setAttribute("login", self.conf["login"])
userNode.setAttribute("password", self.conf["password"])
sessionNode.appendChild(userNode)
if args.has_key("start-apps"): # launch applications at the session startup
startappsNode = doc.createElement("start")
for appid in args["start-apps"]:
appNode = doc.createElement("application")
appNode.setAttribute("id", appid)
startappsNode.appendChild(appNode)
sessionNode.appendChild(startappsNode)
doc.appendChild(sessionNode)
request = urllib2.Request(url, doc.toxml())
try:
url = self.urlOpener.open(request)
except urllib2.HTTPError, exc:
if exc.code == 500:
Logger.info("The service is not available")
return False
Logger.debug("HTTP request return code %d (%s)" % (exc.code, exc.msg))
return False
示例7: txt_export
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def txt_export(filepath):
doc = Document()
root = doc.createElement('data')
doc.appendChild(root)
for sce in bpy.data.scenes :
#create a scene
scene = doc.createElement('scene')
scene.setAttribute('name', sce.name)
root.appendChild(scene)
for obj in sce.objects :
if obj.type == 'FONT':
#add object element
object = doc.createElement('object')
object.setAttribute('name', obj.name)
txt_node = doc.createTextNode(obj.data.body)
object.appendChild(txt_node)
scene.appendChild(object)
#write to a file
file_handle = open(filepath,"wb")
file_handle.write(bytes(doc.toprettyxml(indent='\t'), 'UTF-8'))
file_handle.close()
示例8: save
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def save(self, filename=None):
if filename is None:
filename = self.filename
# this means that self.filename is also None
if filename is None:
# Create a save file dialog
from global_vars import CAIDWorkGroupwildcard
dialog = wx.FileDialog ( None\
, style = wx.SAVE | wx.OVERWRITE_PROMPT\
, wildcard=CAIDWorkGroupwildcard)
# Show the dialog and get user input
if dialog.ShowModal() == wx.ID_OK:
filename = dialog.GetPath()
self.filename = filename
# The user did not select anything
else:
print('Nothing was selected.')
# Destroy the dialog
dialog.Destroy()
# ... create xml doc
from xml.dom.minidom import Document
# Create the minidom document
doc = Document()
# Create the <theme> base element
rootElt = self.viewer.theme.save(doc=doc)
# Create the <caid> base element
rootElt = doc.createElement("caid")
# set camera attributs
eye = self.viewer.lookAt.GetEye()
rootElt.setAttribute("eye", str(eye))
center = self.viewer.lookAt.GetCenter()
rootElt.setAttribute("center", str(center))
up = self.viewer.lookAt.GetUp()
rootElt.setAttribute("up", str(up))
doc.appendChild(rootElt)
# ...
# ...
themeElt, doc = self.viewer.theme.save(doc=doc)
rootElt.appendChild(themeElt)
# ...
# ...
from caid.io import XML
io = XML()
for geo in self.list_geo:
geo.save_attributs()
geoElt = doc.createElement("geometry")
doc = io.geotoxml(geo, doc, geoElt)
rootElt.appendChild(geoElt)
# ...
if filename is not None:
with open( filename, 'w' ) as f:
f.write( doc.toprettyxml() )
else:
print("No file was specified")
示例9: CopyBinaries
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def CopyBinaries(out_dir):
"""cp out/Release/<pak> out/Release/xwalk_core_library/res/raw/<pak>
cp out/Release/lib.java/<lib> out/Release/xwalk_core_library/libs/<lib>
cp out/Release/xwalk_core_shell_apk/libs/*
out/Release/xwalk_core_library/libs
"""
print 'Copying binaries...'
# Copy assets.
res_raw_dir = os.path.join(
out_dir, LIBRARY_PROJECT_NAME, 'res', 'raw')
res_value_dir = os.path.join(
out_dir, LIBRARY_PROJECT_NAME, 'res', 'values')
if not os.path.exists(res_raw_dir):
os.mkdir(res_raw_dir)
if not os.path.exists(res_value_dir):
os.mkdir(res_value_dir)
paks_to_copy = [
'icudtl.dat',
'xwalk.pak',
]
pak_list_xml = Document()
resources_node = pak_list_xml.createElement('resources')
string_array_node = pak_list_xml.createElement('string-array')
string_array_node.setAttribute('name', 'xwalk_resources_list')
pak_list_xml.appendChild(resources_node)
resources_node.appendChild(string_array_node)
for pak in paks_to_copy:
source_file = os.path.join(out_dir, pak)
target_file = os.path.join(res_raw_dir, pak)
shutil.copyfile(source_file, target_file)
item_node = pak_list_xml.createElement('item')
item_node.appendChild(pak_list_xml.createTextNode(pak))
string_array_node.appendChild(item_node)
pak_list_file = open(os.path.join(res_value_dir,
'xwalk_resources_list.xml'), 'w')
pak_list_xml.writexml(pak_list_file, newl='\n', encoding='utf-8')
pak_list_file.close()
# Copy jar files to libs.
libs_dir = os.path.join(out_dir, LIBRARY_PROJECT_NAME, 'libs')
if not os.path.exists(libs_dir):
os.mkdir(libs_dir)
libs_to_copy = [
'xwalk_core_library_java_app_part.jar',
'xwalk_core_library_java_library_part.jar',
]
for lib in libs_to_copy:
source_file = os.path.join(out_dir, 'lib.java', lib)
target_file = os.path.join(libs_dir, lib)
shutil.copyfile(source_file, target_file)
# Copy native libraries.
source_dir = os.path.join(out_dir, XWALK_CORE_SHELL_APK, 'libs')
target_dir = libs_dir
distutils.dir_util.copy_tree(source_dir, target_dir)
示例10: generate_profile_xml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def generate_profile_xml(self, user_info, pac_url, vpn_bypass_except):
doc = Document()
root = doc.createElement('parameters')
doc.appendChild(root)
item0 = doc.createElement('extra')
item0.setAttribute('key', 'com.websense.android.wms.extra.PROXY_CONFIGURATION_ACTION')
item0.setAttribute('value', 'com.websense.android.wms.SET_PROXY_CONFIGURATION')
root.appendChild(item0)
item1 = doc.createElement('extra')
item1.setAttribute('key', 'com.websense.android.wms.extra.PROXY_PAC_FILE_URL')
#add param for the url
updated_pac_url = self.update_pacfile_type(pac_url)
item1.setAttribute('value', updated_pac_url)
root.appendChild(item1)
item2 = doc.createElement('extra')
item2.setAttribute('key', 'com.websense.android.wms.extra.PROXY_AUTH_STRING')
item2.setAttribute('value', str(user_info))
root.appendChild(item2)
item3 = doc.createElement('extra')
item3.setAttribute('key', 'com.websense.android.wms.extra.PACKAGE_NAME')
item3.setAttribute('value', 'com.thirdparty.mdmapplication')
root.appendChild(item3)
#add rules for local network accesss
self.add_vpn_ondemandrules(doc, root, vpn_bypass_except)
dd = doc.toprettyxml(indent="\t").encode('UTF-8')
return dd
示例11: printInherTree
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def printInherTree(self):
"""Creates and print out minidom structure => inheritance tree of whole Model"""
# create minidom-document
doc = Document()
# create model element
model = doc.createElement("model")
doc.appendChild(model)
# loop through all parent/base classes
for cl in self.classInstances:
if len(cl.inheritance) == 0:
entry = doc.createElement("class")
entry.setAttribute("name", cl.name)
entry.setAttribute("kind", cl.kind)
model.appendChild(entry)
children = self.__findInheritanceRecursive(cl.name)
if len(children) != 0:
for ch in children:
entry.appendChild(ch)
# else:
# entry.appendChild(Document().createTextNode("")) # insert empty node, to prevent having self closing node
elif len(cl.inheritance) > 1: # check if conflict in the cl is possible
if self.detectConflict(cl, cl):
# print("conflict")
raise Exception("Conflict in class: "+cl.name)
doc.writexml(outputSrc, "", " "*indentation, "\n", encoding="utf-8")
示例12: todaysNews
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def todaysNews():
query = News.all()
query.order("-createdAt")
results = query.fetch(limit=1)
mostRecentNews = results.pop()
# Create the minidom level document
doc = Document()
newsElement = doc.createElement("news")
doc.appendChild(newsElement)
#headline
headlineElement = doc.createElement("headline")
headline = doc.createTextNode(mostRecentNews.headline)
headlineElement.appendChild(headline)
newsElement.appendChild(headlineElement)
#content
contentElement = doc.createElement("content")
content = doc.createTextNode(mostRecentNews.content)
contentElement.appendChild(content)
newsElement.appendChild(contentElement)
#date
dateElement = doc.createElement("date")
date = doc.createTextNode(str(mostRecentNews.createdAt))
dateElement.appendChild(date)
newsElement.appendChild(dateElement)
out = doc.toxml()
return out
示例13: snapshots
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def snapshots(job_tracking_id,file_id):
try:
print "<snapshots> job_tracking_id: %s - file_id: %s" % (job_tracking_id,file_id)
# Prepare the answer XML
doc = Document()
# Connect to the database
db = MySQLdb.connect(sgjp_db_host,sgjp_db_user,sgjp_db_password,sgjp_db_name)
cursor=db.cursor()
# Prepares the query
query="""select snapshot_ts from sgjp_snapshots where job_tracking_id=%s and file_id=%s order by 1 asc;""" % (job_tracking_id,file_id)
print "query: %s"%query
cursor.execute(query)
results = cursor.fetchall()
doc_snapshots = doc.createElement("snapshots")
doc.appendChild(doc_snapshots)
for row in results:
snapshot_ts = row[0]
print "\t<snapshot_record> job_tracking_id: %s - file_id: %s - snapshot_ts: %s" % (job_tracking_id,file_id,snapshot_ts)
# Put output into the XML
doc_snapshots_snapshot = doc.createElement("snapshot")
doc_snapshots_snapshot.setAttribute("job_tracking_id", "%s"%job_tracking_id)
doc_snapshots_snapshot.setAttribute("file_id", "%s"%file_id)
doc_snapshots_snapshot.setAttribute("snapshot_ts", "%s"%snapshot_ts)
doc_snapshots.appendChild(doc_snapshots_snapshot)
# Close connection
db.close()
except MySQLdb.Error, e:
print 'exception!!!'
db.close()
doc_error = doc.createElement("error")
doc.appendChild(doc_error)
doc_error.setAttribute("message", "Unable to get job files")
doc_error.setAttribute("sqlerr", repr(e))
doc_error.setAttribute("query", query)
示例14: encode
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def encode(self):
# Create the XML document
doc = Document()
signed_cred = doc.createElement("signed-credential")
# Declare namespaces
# Note that credential/policy.xsd are really the PG schemas
# in a PL namespace.
# Note that delegation of credentials between the 2 only really works
# cause those schemas are identical.
# Also note these PG schemas talk about PG tickets and CM policies.
signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.geni.net/resources/credential/2/credential.xsd")
signed_cred.setAttribute("xsi:schemaLocation", "http://www.planet-lab.org/resources/sfa/ext/policy/1 http://www.planet-lab.org/resources/sfa/ext/policy/1/policy.xsd")
# PG says for those last 2:
# signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")
# signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")
doc.appendChild(signed_cred)
# Fill in the <credential> bit
cred = doc.createElement("credential")
cred.setAttribute("xml:id", self.get_refid())
signed_cred.appendChild(cred)
append_sub(doc, cred, "type", "abac")
# Stub fields
append_sub(doc, cred, "serial", "8")
append_sub(doc, cred, "owner_gid", '')
append_sub(doc, cred, "owner_urn", '')
append_sub(doc, cred, "target_gid", '')
append_sub(doc, cred, "target_urn", '')
append_sub(doc, cred, "uuid", "")
if not self.expiration:
self.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(seconds=DEFAULT_CREDENTIAL_LIFETIME))
self.expiration = self.expiration.replace(microsecond=0)
if self.expiration.tzinfo is not None and self.expiration.tzinfo.utcoffset(self.expiration) is not None:
# TZ aware. Make sure it is UTC
self.expiration = self.expiration.astimezone(tz.tzutc())
append_sub(doc, cred, "expires", self.expiration.strftime('%Y-%m-%dT%H:%M:%SZ')) # RFC3339
abac = doc.createElement("abac")
rt0 = doc.createElement("rt0")
abac.appendChild(rt0)
cred.appendChild(abac)
append_sub(doc, rt0, "version", "1.1")
head = self.createABACElement(doc, "head", self.get_head())
rt0.appendChild(head)
for tail in self.get_tails():
tailEle = self.createABACElement(doc, "tail", tail)
rt0.appendChild(tailEle)
# Create the <signatures> tag
signatures = doc.createElement("signatures")
signed_cred.appendChild(signatures)
# Get the finished product
self.xml = doc.toxml("utf-8")
示例15: featuresElement
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createElement [as 别名]
def featuresElement(pae=False, nonpae=False, acpi=False, apic=False):
"""
Creates a <features> element, a child of L{domain element
<domainElement>}, that specifies mutually exclusive hypervisor features.
@param pae: physical address extension mode
@type pae: boolean
@param nonpae: physical address extension mode
@type nonpae: boolean
@param acpi: acpi support
@type acpi: boolean
@param apic: apic support
@type apic: boolean
@return: <features> element
@rtype: DOM Element
"""
document = Document()
features = document.createElement('features')
if pae:
features.appendChild(document.createElement('pae'))
if nonpae:
features.appendChild(document.createElement('nonpae'))
if acpi:
features.appendChild(document.createElement('acpi'))
if apic:
features.appendChild(document.createElement('apic'))
return features