我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.dom.minidom.Document()。
def getXMLResults(self): if self.injResults or self.fingerResults: doc=Document() wml = doc.createElement("sqPyfiaResults") doc.appendChild(wml) result=doc.createElement("SqlInjResult") wml.appendChild(result) result.appendChild(self.req.getXML(doc)) if self.injResults or self.fingerResults: for i in self.injResults: result.appendChild(i.getXML(doc)) for i in self.fingerResults: result.appendChild(i.getXML(doc)) return doc else: return None
def getXMLResults(self): success=False doc=Document() wml = doc.createElement("GazpacioResults") doc.appendChild(wml) result=doc.createElement("XssResult") wml.appendChild(result) result.appendChild(self.req.getXML(doc)) for i in self.resultSet: if i[0]: success=True var = doc.createElement("variable") var.setAttribute("name",i[2]) var.setAttribute("method",i[1]) inj = doc.createElement("InjectionsAvailable") inj.appendChild(doc.createTextNode("\r\n".join(i[3]))) var.appendChild(inj) result.appendChild(var) if success: return doc return None
def build_element(self, name, child=None, attrs=None): """Build XML element :param name: :param child: :param attrs: :return: :class:`~xml.dom.minidom.Element` """ if attrs is None: attrs = {} xdoc = minidom.Document() e = xdoc.createElement(name) for attr_k, attr_v in attrs.items(): e.setAttribute(attr_k, attr_v) if child is not None: e.appendChild(child) return e
def dict2xml(data): """Convert dict to xml document.""" document = Document() def create_node(root, node_data): for key, val in node_data.items(): node = document.createElement(key) if isinstance(val, dict): attrs = val.pop('__attrs__', {}) for attr, attr_val in attrs.items(): node.setAttribute(attr, attr_val) create_node(node, val) elif isinstance(val, (tuple, list)): for sub_data in val: create_node(node, sub_data) else: node.appendChild(document.createTextNode(str(val))) root.appendChild(node) create_node(document, data) return document.childNodes[0].toxml()
def __init__(self, flo, program_id=None, program_version=None, compact=False): self._flo = flo self._doc = minidom.Document() root = self._doc.createElement('ADX') self._doc.appendChild(root) header = self._doc.createElement('HEADER') header.appendChild(self._create_node('ADIF_VER', self.adif_ver)) tmp_data = datetime.datetime.utcnow().strftime('%Y%m%d %H%M%S') header.appendChild(self._create_node('CREATED_TIMESTAMP', tmp_data)) if program_id: header.appendChild(self._create_node('PROGRAMID', program_id)) if program_version: header.appendChild(self._create_node('PROGRAMVERSION', program_version)) else: from hamutils import __version__ as hamutils_version header.appendChild(self._create_node('PROGRAMID', 'hamutils')) header.appendChild(self._create_node('PROGRAMVERSION', hamutils_version)) root.appendChild(header) self._records = self._doc.createElement('RECORDS') root.appendChild(self._records) self._compact = compact
def testLegalChildren(self): dom = Document() elem = dom.createElement('element') text = dom.createTextNode('text') self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text) dom.appendChild(elem) self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text, elem) self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text, elem) nodemap = elem.attributes self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem, text) self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS, text) elem.appendChild(text) dom.unlink()
def testAddAttr(self): dom = Document() child = dom.appendChild(dom.createElement("abc")) child.setAttribute("def", "ghi") self.confirm(child.getAttribute("def") == "ghi") self.confirm(child.attributes["def"].value == "ghi") child.setAttribute("jkl", "mno") self.confirm(child.getAttribute("jkl") == "mno") self.confirm(child.attributes["jkl"].value == "mno") self.confirm(len(child.attributes) == 2) child.setAttribute("def", "newval") self.confirm(child.getAttribute("def") == "newval") self.confirm(child.attributes["def"].value == "newval") self.confirm(len(child.attributes) == 2) dom.unlink()
def testUserData(self): dom = Document() n = dom.createElement('e') self.confirm(n.getUserData("foo") is None) n.setUserData("foo", None, None) self.confirm(n.getUserData("foo") is None) n.setUserData("foo", 12, 12) n.setUserData("bar", 13, 13) self.confirm(n.getUserData("foo") == 12) self.confirm(n.getUserData("bar") == 13) n.setUserData("foo", None, None) self.confirm(n.getUserData("foo") is None) self.confirm(n.getUserData("bar") == 13) handler = self.UserDataHandler() n.setUserData("bar", 12, handler) c = n.cloneNode(1) self.confirm(handler.called and n.getUserData("bar") is None and c.getUserData("bar") == 13) n.unlink() c.unlink() dom.unlink()
def export_list_to_xacro(list, filename): """Export all links containing a string and its parent joint. :param : list, list of strings to look for :param : filename, absolute path of the file to write to """ global robot, OUTPUT doc = Document() root = doc.createElement('robot') doc.appendChild(root) root.setAttribute("xmlns:xacro", "http://www.ros.org/wiki/xacro") print ('exporting ' + os.path.basename(filename)) for string in list: for link in robot.links: if robot.links[link].name.find(string) != -1: root.appendChild(robot.links[link].to_xml(doc)) for joint in robot.joints: if robot.joints[joint].child == robot.links[link].name: root.appendChild(robot.joints[joint].to_xml(doc)) write_comments_in_xacro(doc, filename)
def to_xml(self, orderbytree=False, orderbytype=False): doc = Document() root = doc.createElement("robot") doc.appendChild(root) root.setAttribute("name", self.name) baselink = self.parent_map if orderbytree: # Walk child map sequentially and export pass if orderbytype: pass for element in self.elements: root.appendChild(element.to_xml(doc)) return doc.toprettyxml()
def write_xlsx_to_xml(data, savename): # ??dom?? doc = Document() # ????? root = doc.createElement('root') # ??student?? student = doc.createElement('numbers') # ?????dom? doc.appendChild(root) # ?student???????? root.appendChild(student) # ???? comment = doc.createComment('\n ????\n') student.appendChild(comment) # ???? text_node = doc.createTextNode(str(data)) student.appendChild(text_node) # ???xml?? with open(savename, 'w', encoding='utf-8') as f: doc.writexml(f, addindent=' ', newl='\n', encoding='utf-8')
def write_xlsx_to_xml(datadict, savename): # ??dom?? doc = Document() # ????? root = doc.createElement('root') # ??student?? student = doc.createElement('student') # ?????dom? doc.appendChild(root) # ?student???????? root.appendChild(student) # ???? comment = doc.createComment('\n ?????\n "id" : [???????????]\n') student.appendChild(comment) # ???? text_node = doc.createTextNode(str(datadict)) student.appendChild(text_node) # ???xml?? with open(savename, 'w', encoding='utf-8') as f: doc.writexml(f, addindent=' ', newl='\n', encoding='utf-8')
def write_xlsx_to_xml(datadict, savename): # ??dom?? doc = Document() # ????? root = doc.createElement('root') # ??student?? student = doc.createElement('city') # ?????dom? doc.appendChild(root) # ?student???????? root.appendChild(student) # ???? comment = doc.createComment('\n ????\n') student.appendChild(comment) # ???? text_node = doc.createTextNode(str(datadict)) student.appendChild(text_node) # ???xml?? with open(savename, 'w', encoding='utf-8') as f: doc.writexml(f, addindent=' ', newl='\n', encoding='utf-8')
def testNamedNodeMapSetItem(self): dom = Document() elem = dom.createElement('element') attrs = elem.attributes attrs["foo"] = "bar" a = attrs.item(0) self.confirm(a.ownerDocument is dom, "NamedNodeMap.__setitem__() sets ownerDocument") self.confirm(a.ownerElement is elem, "NamedNodeMap.__setitem__() sets ownerElement") self.confirm(a.value == "bar", "NamedNodeMap.__setitem__() sets value") self.confirm(a.nodeValue == "bar", "NamedNodeMap.__setitem__() sets nodeValue") elem.unlink() dom.unlink()
def testCloneDocumentDeep(self): doc = parseString("<?xml version='1.0'?>\n" "<!-- comment -->" "<!DOCTYPE doc [\n" "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n" "]>\n" "<doc attr='value'/>") doc2 = doc.cloneNode(1) self.confirm(not (doc.isSameNode(doc2) or doc2.isSameNode(doc)), "testCloneDocumentDeep: document objects not distinct") self.confirm(len(doc.childNodes) == len(doc2.childNodes), "testCloneDocumentDeep: wrong number of Document children") self.confirm(doc2.documentElement.nodeType == Node.ELEMENT_NODE, "testCloneDocumentDeep: documentElement not an ELEMENT_NODE") self.confirm(doc2.documentElement.ownerDocument.isSameNode(doc2), "testCloneDocumentDeep: documentElement owner is not new document") self.confirm(not doc.documentElement.isSameNode(doc2.documentElement), "testCloneDocumentDeep: documentElement should not be shared") if doc.doctype is not None: # check the doctype iff the original DOM maintained it self.confirm(doc2.doctype.nodeType == Node.DOCUMENT_TYPE_NODE, "testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE") self.confirm(doc2.doctype.ownerDocument.isSameNode(doc2)) self.confirm(not doc.doctype.isSameNode(doc2.doctype))
def test_toprettyxml_with_adjacent_text_nodes(self): # see issue #4147, adjacent text nodes are indented normally dom = Document() elem = dom.createElement(u'elem') elem.appendChild(dom.createTextNode(u'TEXT')) elem.appendChild(dom.createTextNode(u'TEXT')) dom.appendChild(elem) decl = '<?xml version="1.0" ?>\n' self.assertEqual(dom.toprettyxml(), decl + '<elem>\n\tTEXT\n\tTEXT\n</elem>\n')
def xml(self): """ This function writes the individual to an xml format. Returns ---------- xml individual : str The xml string of the individual. """ doc = Document() if self.live: status = "true" else: status = "false" xml_doc = analyse_xml.create_xml_individual(doc, self.id, self.generation, status, self.genotype, self.derivedparams, self.scores) return xml_doc.toxml()
def create_childnode(node_name, parent_node, value, doc): """ This function creates a node. Parameters ---------- node_name : str The name of the node to be created. parent_node : xml minidom Node The parent node. value : str The value of the node. doc : xml minidom Document The document to append the created node into. """ childnode = doc.createElement(node_name) value = doc.createTextNode(value) childnode.appendChild(value) parent_node.appendChild(childnode)
def _update(self, xml): if xml is None: return if isinstance(xml, Document): xml = xml.documentElement for field in xml.getElementsByTagName('field'): name = field.getAttribute('name') if name == 'updated': self.updated = int(self._text(field.getElementsByTagName('value')[0])) elif name == 'updaterName': self.updater_name = self._text(field.getElementsByTagName('value')[0]) elif name == 'links': pass else: self.fields.append(ChangeField(field, self.youtrack)) for comment in xml.getElementsByTagName('comment'): self.comments.append(comment.getAttribute('text'))
def _update(self, xml): if xml is None: return if isinstance(xml, Document): xml = xml.documentElement self.name = xml.getAttribute("name") users = xml.getElementsByTagName("user") if users is not None: self.users = [self.youtrack.getUser(v.getAttribute("login")) for v in users] else: self.users = [] groups = xml.getElementsByTagName("userGroup") if groups is not None: self.groups = [self.youtrack.getGroup(v.getAttribute("name")) for v in groups] else: self.groups = []
def testRemoveAttributeNode(self): dom = Document() child = dom.appendChild(dom.createElement("foo")) child.setAttribute("spam", "jam") self.confirm(len(child.attributes) == 1) node = child.getAttributeNode("spam") self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNode, None) child.removeAttributeNode(node) self.confirm(len(child.attributes) == 0 and child.getAttributeNode("spam") is None) dom2 = Document() child2 = dom2.appendChild(dom2.createElement("foo")) node2 = child2.getAttributeNode("spam") self.assertRaises(xml.dom.NotFoundErr, child2.removeAttributeNode, node2) dom.unlink()
def test_application_content_type_default_xml_mimidom(self): from xml.dom.minidom import Document, parseString @GET("/asd") @called_with def asd(): doc = Document() root = doc.createElement("root") doc.appendChild(root) return doc result = self.get("/asd") self.assertEqual(HTTP_OK, self.status) self.assertCalledWith(asd) self.assertTrue(CONTENT_TYPE in self.headers) self.assertEqual(MIME_XML, self.headers[CONTENT_TYPE]) self.assertEqual(parseString("<root/>").toxml(), result)
def run(self): # we should probably do this somewhere else doc = Document() lfde = doc.createElement("lfde") doc.appendChild(lfde) bootscheme = doc.createElement("bootscheme") bootscheme.appendChild(doc.createTextNode(self.choices.boot_scheme)) lfde.appendChild(bootscheme) if os.path.exists("/etc/lfde") == False: os.makedirs("/etc/lfde") config_fh = open("/etc/lfde/config.xml", "w") config_fh.write(doc.toprettyxml()) config_fh.close() self.progress_callback(1.0)
def setOutputFile(self): ''' Initiates the xml file from the configuration. ''' if (conf.xmlFile): try: self._outputFile = conf.xmlFile self.__root = None if os.path.exists(self._outputFile): try: self.__doc = xml.dom.minidom.parse(self._outputFile) self.__root = self.__doc.childNodes[0] except ExpatError: self.__doc = Document() self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING) if self.__root is None: self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME) self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR)) self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME)) self.__doc.appendChild(self.__root) except IOError: raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)