本文整理汇总了Python中xml.dom.minidom.Document.appendChild方法的典型用法代码示例。如果您正苦于以下问题:Python Document.appendChild方法的具体用法?Python Document.appendChild怎么用?Python Document.appendChild使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.dom.minidom.Document
的用法示例。
在下文中一共展示了Document.appendChild方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: doStartSession
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [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
示例2: write_xml_hypergraph
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [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 appendChild [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: createBalanceSheetPDF
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def createBalanceSheetPDF(self):
out = open("/tmp/balancesheet_"+str(self.id)+".xml","w")
doc = Document()
main = doc.createElement("koalixaccountingbalacesheet")
calculationUnitName = doc.createElement("calculationUnitName")
calculationUnitName.appendChild(doc.createTextNode(self.__unicode__()))
main.appendChild(calculationUnitName)
calculationUnitTo = doc.createElement("calculationUnitTo")
calculationUnitTo.appendChild(doc.createTextNode(self.end.year.__str__()))
main.appendChild(calculationUnitTo)
calculationUnitFrom = doc.createElement("calculationUnitFrom")
calculationUnitFrom.appendChild(doc.createTextNode(self.begin.year.__str__()))
main.appendChild(calculationUnitFrom)
accountNumber = doc.createElement("AccountNumber")
accounts = Account.objects.all()
for account in list(accounts) :
currentValue = account.valueNow(self)
if (currentValue != 0):
currentAccountElement = doc.createElement("Account")
accountNumber = doc.createElement("AccountNumber")
accountNumber.appendChild(doc.createTextNode(account.accountNumber.__str__()))
currentValueElement = doc.createElement("currentValue")
currentValueElement.appendChild(doc.createTextNode(currentValue.__str__()))
accountNameElement = doc.createElement("accountName")
accountNameElement.appendChild(doc.createTextNode(account.title))
currentAccountElement.setAttribute("accountType", account.accountType.__str__())
currentAccountElement.appendChild(accountNumber)
currentAccountElement.appendChild(accountNameElement)
currentAccountElement.appendChild(currentValueElement)
main.appendChild(currentAccountElement)
doc.appendChild(main)
out.write(doc.toprettyxml(indent=" "))
system("fop -c /var/www/koalixcrm/verasans.xml -xml /tmp/balancesheet_"+str(self.id)+".xml -xsl /var/www/koalixcrm/balancesheet.xsl -pdf /tmp/balancesheet_"+str(self.id)+".pdf")
return "/tmp/balancesheet_"+str(self.id)+".pdf"
示例5: send_server_status
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def send_server_status(self, status):
doc = Document()
rootNode = doc.createElement('server')
rootNode.setAttribute("status", status)
doc.appendChild(rootNode)
response = self.send_packet("/server/status", doc)
if response is False:
Logger.warn("SMRequest::send_server_status Unable to send packet")
return False
document = self.get_response_xml(response)
if document is None:
Logger.warn("SMRequest::send_server_status response not XML")
return False
rootNode = document.documentElement
if rootNode.nodeName != "server":
Logger.error("SMRequest::send_server_status response not valid %s"%(rootNode.toxml()))
return False
if not rootNode.hasAttribute("name") or rootNode.getAttribute("name") != self.name:
Logger.error("SMRequest::send_server_status response invalid name")
return False
if not rootNode.hasAttribute("status") or rootNode.getAttribute("status") != status:
Logger.error("SMRequest::send_server_status response invalid status")
return False
return True
示例6: testTaxes3
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def testTaxes3(self):
doc = Document()
parent_node = doc.createElement('parent_node')
doc.appendChild(parent_node)
data = {
'default-tax-table': {
'tax-rules': [
{
'shipping-taxed': False,
'rate': 0.08375,
'tax-area': {
'us-zip-area': ['100*'],
}
},
{
'shipping-taxed': True,
'rate': 0.04,
'tax-area': {
'us-state-area': ['NY'],
}
}
]
}
}
self.gc._taxes(doc, parent_node, data)
xml1 = "<parent_node><tax-tables><default-tax-table>\
<tax-rules><default-tax-rule><shipping-taxed>false</shipping-taxed>\
<rate>0.08375</rate><tax-area><us-zip-area><zip-pattern>100*</zip-pattern>\
</us-zip-area></tax-area></default-tax-rule>\
<default-tax-rule><shipping-taxed>true</shipping-taxed>\
<rate>0.04</rate><tax-area><us-state-area><state>NY</state></us-state-area>\
</tax-area></default-tax-rule>\
</tax-rules></default-tax-table></tax-tables></parent_node>"
doc_good = parseString(xml1)
self.assertEquals(doc.toxml(), doc_good.toxml())
示例7: testShippingExclude
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def testShippingExclude(self):
doc = Document()
parent_node = doc.createElement('parent_node')
doc.appendChild(parent_node)
data = {
'us-state-area': ['AK','HI'],
'us-zip-area': ['90210', '04005', '04092'],
'us-country-area': 'CONTINENTAL_48',
'world-area': True,
'postal-area': [{
'country-code': 'US',
'postal-code-pattern': ['94043', '90211'],
},
],
}
self.gc._shipping_allowed_excluded(doc, parent_node, data)
xml1 = "<parent_node><us-state-area><state>AK</state></us-state-area>\
<us-state-area><state>HI</state></us-state-area>\
<us-zip-area><zip-pattern>90210</zip-pattern></us-zip-area>\
<us-zip-area><zip-pattern>04005</zip-pattern></us-zip-area>\
<us-zip-area><zip-pattern>04092</zip-pattern></us-zip-area>\
<us-country-area country-area='CONTINENTAL_48'/>\
<world-area/>\
<postal-area><country-code>US</country-code>\
<postal-code-pattern>94043</postal-code-pattern>\
<postal-code-pattern>90211</postal-code-pattern></postal-area>\
</parent_node>"
doc_good = parseString(xml1)
self.assertEquals(doc.toxml(), doc_good.toxml())
示例8: DictToXml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
class DictToXml(object): # pylint: disable=too-few-public-methods
"""Map dictionary into XML"""
def __init__(self, structure):
self.doc = Document()
root_name = str(structure.keys()[0])
root = self.doc.createElement(root_name)
self.doc.appendChild(root)
self._build(root, structure[root_name])
def _build(self, parent, structure):
if isinstance(structure, dict):
for node_name in structure:
tag = self.doc.createElement(node_name)
parent.appendChild(tag)
self._build(tag, structure[node_name])
elif isinstance(structure, list):
for node_structure in structure:
self._build(parent, node_structure)
elif structure is None:
return
else:
node_data = str(structure)
tag = self.doc.createTextNode(node_data)
parent.appendChild(tag)
def __str__(self):
# TODO implement separate method for pretty print
return self.doc.toxml()
示例9: parse_type_of
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def parse_type_of(obj):
"""
@return: A C{ParsedDocstring} that encodes the type of the given
object.
@rtype: L{ParsedDocstring}
@param obj: The object whose type should be returned as DOM document.
@type obj: any
"""
# This is a bit hackish; oh well. :)
from epydoc.markup.epytext import ParsedEpytextDocstring
from xml.dom.minidom import Document
doc = Document()
epytext = doc.createElement('epytext')
para = doc.createElement('para')
doc.appendChild(epytext)
epytext.appendChild(para)
if type(obj) is types.InstanceType:
link = doc.createElement('link')
name = doc.createElement('name')
target = doc.createElement('target')
para.appendChild(link)
link.appendChild(name)
link.appendChild(target)
name.appendChild(doc.createTextNode(str(obj.__class__.__name__)))
target.appendChild(doc.createTextNode(str(obj.__class__)))
else:
code = doc.createElement('code')
para.appendChild(code)
code.appendChild(doc.createTextNode(type(obj).__name__))
return ParsedEpytextDocstring(doc)
示例10: txt_export
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [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()
示例11: encode
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [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")
示例12: testLegalChildren
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def testLegalChildren():
dom = Document()
elem = dom.createElement('element')
text = dom.createTextNode('text')
try: dom.appendChild(text)
except HierarchyRequestErr: pass
else:
print "dom.appendChild didn't raise HierarchyRequestErr"
dom.appendChild(elem)
try: dom.insertBefore(text, elem)
except HierarchyRequestErr: pass
else:
print "dom.appendChild didn't raise HierarchyRequestErr"
try: dom.replaceChild(text, elem)
except HierarchyRequestErr: pass
else:
print "dom.appendChild didn't raise HierarchyRequestErr"
nodemap = elem.attributes
try: nodemap.setNamedItem(text)
except HierarchyRequestErr: pass
else:
print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"
try: nodemap.setNamedItemNS(text)
except HierarchyRequestErr: pass
else:
print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"
elem.appendChild(text)
dom.unlink()
示例13: impl_create_pydevproject
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def impl_create_pydevproject(self, system_path, user_path):
# create a pydevproject file
doc = Document()
doc.appendChild(doc.createProcessingInstruction('eclipse-pydev', 'version="1.0"'))
pydevproject = doc.createElement('pydev_project')
prop = self.add(doc, pydevproject,
'pydev_property',
'python %d.%d'%(sys.version_info[0], sys.version_info[1]))
prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_VERSION')
prop = self.add(doc, pydevproject, 'pydev_property', 'Default')
prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_INTERPRETER')
# add waf's paths
wafadmin = [p for p in system_path if p.find('wafadmin') != -1]
if wafadmin:
prop = self.add(doc, pydevproject, 'pydev_pathproperty',
{'name':'org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH'})
for i in wafadmin:
self.add(doc, prop, 'path', i)
if user_path:
prop = self.add(doc, pydevproject, 'pydev_pathproperty',
{'name':'org.python.pydev.PROJECT_SOURCE_PATH'})
for i in user_path:
self.add(doc, prop, 'path', '/${PROJECT_DIR_NAME}/'+i)
doc.appendChild(pydevproject)
return doc
示例14: do_call_exit
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def do_call_exit(self):
if d.sessionProperties["persistent"]:
mode = "suspend"
else:
mode = "logout"
document = Document()
rootNode = document.createElement("logout")
rootNode.setAttribute("mode", mode)
document.appendChild(rootNode)
url = "%s/logout.php" % (self.base_url)
request = urllib2.Request(url)
request.add_header("Content-type", "text/xml; charset=UTF-8")
request.add_data(document.toxml())
try:
url = self.urlOpener.open(request)
except urllib2.HTTPError, exc:
if exc.code == 500:
Logger.warn("Service failurek")
return False
Logger.debug("HTTP request return code %d (%s)" % (exc.code, exc.msg))
Logger.debug(" * return: %s" % (str(exc.read())))
return False
示例15: test_node_to_dict2
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import appendChild [as 别名]
def test_node_to_dict2():
"""
should return dict of node double nested
"""
doc = Document()
outer = doc.createElement("outer")
doc.appendChild(outer)
mid1 = doc.createElement("mid1")
outer.appendChild(mid1)
mid2 = doc.createElement("mid2")
outer.appendChild(mid2)
inner1 = doc.createElement("inner1")
inner2 = doc.createElement("inner2")
mid1.appendChild(inner1)
mid2.appendChild(inner2)
inner1_text = doc.createTextNode("one")
inner2_text = doc.createTextNode("two")
inner1.appendChild(inner1_text)
inner2.appendChild(inner2_text)
expected_dict = {'outer': {'mid2': {'inner2': 'two'}, 'mid1': {'inner1': 'one'}}}
xml_dict = xml.node_to_dict(doc)
assert xml_dict == expected_dict