def test_fixAPI(self): """ The element passed to L{tree.fixAPI} has all of its children with the I{API} class rewritten to contain links to the API which is referred to by the text they contain. """ parent = dom.Element('div') link = dom.Element('span') link.setAttribute('class', 'API') text = dom.Text() text.data = 'foo' link.appendChild(text) parent.appendChild(link) tree.fixAPI(parent, 'http://example.com/%s') self.assertEqual( parent.toxml(), '<div><span class="API">' '<a href="http://example.com/foo" title="foo">foo</a>' '</span></div>')
def _toxml(self, dom): """ Return a XML Representation of the object """ if self.id not in [None, 'None']: element = minidom.Element("customer_id") node_txt = dom.createTextNode(str(self.id)) element.appendChild(node_txt) return element else: return super(ChargifyCustomer, self)._toxml(dom)
def _createNode(accessible, parentElement): e = minidom.Element("accessible") e.attributes["name"] = accessible.name e.attributes["role"] = str(int(accessible.getRole())) e.attributes["description"] = accessible.description for i in range(0, accessible.childCount): _createNode(accessible.getChildAtIndex(i), e) parentElement.appendChild(e)
def start_element_handler(self, name, attributes): if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) else: uri = EMPTY_NAMESPACE qname = name localname = None prefix = EMPTY_PREFIX node = minidom.Element(qname, uri, prefix, localname) node.ownerDocument = self.document _append_child(self.curNode, node) self.curNode = node if self._ns_ordered_prefixes: for prefix, uri in self._ns_ordered_prefixes: if prefix: a = minidom.Attr(_intern(self, 'xmlns:' + prefix), XMLNS_NAMESPACE, prefix, "xmlns") else: a = minidom.Attr("xmlns", XMLNS_NAMESPACE, "xmlns", EMPTY_PREFIX) # we're only interested in the URI as text at this point uri = uri or "" d = a.childNodes[0].__dict__ d['data'] = d['nodeValue'] = uri d = a.__dict__ d['value'] = d['nodeValue'] = uri d['ownerDocument'] = self.document _set_attribute_node(node, a) del self._ns_ordered_prefixes[:] if attributes: _attrs = node._attrs _attrsNS = node._attrsNS for i in range(0, len(attributes), 2): aname = attributes[i] value = attributes[i + 1] if ' ' in aname: uri, localname, prefix, qname = _parse_ns_name(self, aname) a = minidom.Attr(qname, uri, localname, prefix) _attrs[qname] = a _attrsNS[(uri, localname)] = a else: a = minidom.Attr(aname, EMPTY_NAMESPACE, aname, EMPTY_PREFIX) _attrs[aname] = a _attrsNS[(EMPTY_NAMESPACE, aname)] = a d = a.childNodes[0].__dict__ d['data'] = d['nodeValue'] = value d = a.__dict__ d['ownerDocument'] = self.document d['value'] = d['nodeValue'] = value d['ownerElement'] = node
def test_findNodeJustBefore(self): """ L{tree.findNodeJustBefore} returns the previous sibling of the node it is passed. The list of nodes passed in is ignored. """ parent = dom.Element('div') result = dom.Element('foo') target = dom.Element('bar') parent.appendChild(result) parent.appendChild(target) self.assertIdentical( tree.findNodeJustBefore(target, [parent, result]), result) # Also, support other configurations. This is a really not nice API. newTarget = dom.Element('baz') target.appendChild(newTarget) self.assertIdentical( tree.findNodeJustBefore(newTarget, [parent, result]), result)
def test_setTitleWithChapter(self): """ L{tree.setTitle} includes a chapter number if it is passed one. """ document = dom.Document() parent = dom.Element('div') parent.ownerDocument = document title = dom.Element('title') parent.appendChild(title) titleNodes = [dom.Text()] titleNodes[0].ownerDocument = document titleNodes[0].data = 'foo bar' # Oh yea. The numberer has to agree to put the chapter number in, too. numberer.setNumberSections(True) tree.setTitle(parent, titleNodes, '13') self.assertEqual(title.toxml(), '<title>13. foo bar</title>')
def schreibe_dict(d, dateiname): baum = dom.Document() tag_dict = dom.Element("dictionary") for schluessel, wert in d.items(): tag_eintrag = erstelle_eintrag(schluessel, wert) tag_dict.appendChild(tag_eintrag) baum.appendChild(tag_dict) with open("ver3.xml", "w") as f: baum.writexml(f, "", "\t", "\n")
def to_xml(self): step = Pair('step', self.step) octave = Pair('octave', self.octave) pitch = Dic('pitch', [step, octave]) duration = Pair('duration', self.duration) type = Pair('type', self.type) note = Dic('note', [pitch, duration, type]) for i in range(int(self.dot)): dot = minidom.Element('dot') note.appendChild(dot) self.xml = note return self.xml
def _toxml(self, dom): """ Return a XML Representation of the object """ # log.debug("Converting element to xml....") element = minidom.Element(self.__xmlnodename__) for property, value in self.__dict__.iteritems(): # print "da!", property, value if property == '__ignore__': continue if not property in self.__ignore__ and not inspect.isfunction( value): if property in self.__attribute_types__: if type(value) == list: node = minidom.Element(property) node.setAttribute('type', 'array') for v in value: child = v._toxml(dom) if child is not None: node.appendChild(child) element.appendChild(node) else: #log.debug("Adding element: %s (value: %s)" % (property, value)) try: element.appendChild(value._toxml(dom)) # log.debug("New element contents: %s", element.toprettyxml()) except: pass else: node = minidom.Element(property) node_txt = dom.createTextNode( str(value).encode('ascii', 'xmlcharrefreplace')) node.appendChild(node_txt) element.appendChild(node) else: pass # print "f**k", property, value # print self,self.__ignore__, inspect.isfunction(value) return element
def __init__(self, Filename): """initialise class based on filename args: Filename -- points to XML file """ RdataTSF.__init__(self, Filename) ListLowerStages = self.mod.getElementsByTagName("LowerStage") ListUpperStages = self.mod.getElementsByTagName("UpperStage") LStat = md.Element("TempNode") for Lnode in ListLowerStages: LStat.appendChild(Lnode) LStatList = LStat.getElementsByTagName("FlightStats") LDataList = LStat.getElementsByTagName("FlightData") self.LApoVg = self.GetStatsArray(LStatList, "Apogee") self.LLandVg = self.GetStatsArray(LStatList, "Landing") self.LFpathList = [] for LData in LDataList: self.LFpathList.append(self.Read3VectorFromXML(LData, "Position")) UStat = md.Element("TempNode") for Unode in ListUpperStages: UStat.appendChild(Unode) UStatList = UStat.getElementsByTagName("FlightStats") UDataList = UStat.getElementsByTagName("FlightData") self.UApoVg = self.GetStatsArray(UStatList, "Apogee") self.ULandVg = self.GetStatsArray(UStatList, "Landing") self.UFpathList = [] for UData in UDataList: self.UFpathList.append(self.Read3VectorFromXML(UData, "Position"))
def footnotes(document): """ Find footnotes in the given document, move them to the end of the body, and generate links to them. A footnote is any node with a C{class} attribute set to C{footnote}. Footnote links are generated as superscript. Footnotes are collected in a C{ol} node at the end of the document. @type document: A DOM Node or Document @param document: The input document which contains all of the content to be presented. @return: C{None} """ footnotes = domhelpers.findElementsWithAttribute(document, "class", "footnote") if not footnotes: return footnoteElement = dom.Element('ol') id = 1 for footnote in footnotes: href = dom.parseString('<a href="#footnote-%(id)d">' '<super>%(id)d</super></a>' % vars()).documentElement text = ' '.join(domhelpers.getNodeText(footnote).split()) href.setAttribute('title', text) target = dom.Element('a') target.setAttribute('name', 'footnote-%d' % (id, )) target.childNodes = [footnote] footnoteContent = dom.Element('li') footnoteContent.childNodes = [target] footnoteElement.childNodes.append(footnoteContent) footnote.parentNode.replaceChild(href, footnote) id += 1 body = domhelpers.findNodesNamed(document, "body")[0] header = dom.parseString('<h2>Footnotes</h2>').documentElement body.childNodes.append(header) body.childNodes.append(footnoteElement)
def test_fixAPIBase(self): """ If a node with the I{API} class and a value for the I{base} attribute is included in the DOM passed to L{tree.fixAPI}, the link added to that node refers to the API formed by joining the value of the I{base} attribute to the text contents of the node. """ parent = dom.Element('div') link = dom.Element('span') link.setAttribute('class', 'API') link.setAttribute('base', 'bar') text = dom.Text() text.data = 'baz' link.appendChild(text) parent.appendChild(link) tree.fixAPI(parent, 'http://example.com/%s') self.assertEqual( parent.toxml(), '<div><span class="API">' '<a href="http://example.com/bar.baz" title="bar.baz">baz</a>' '</span></div>')
def create_element(tag_name, namespaceURI=None, prefix=None, localName=None): """:cls: ``xml.dom.Element`` object constructor """ element = DOM.Element(tag_name, namespaceURI, prefix, localName) # if ":" in tag_name: # prefix, local_name = tag_name.split(":") # else: # local_name = tag_name.split(":") # element.prefix = prefix # element.localName = local_name return element
def p_mkannotate(cls, p, comments, links): """ Build the final annotated (html) representation of a paragraph. """ for key, content in comments: textel = minidom.Text() textel.data = cls.ALL_TEXT.xt(content) el = minidom.Element('i') el.setAttribute('class', 'comment') el.appendChild(textel) p = p.replace(key, el.toxml()) for key, content in links: el = minidom.Element('a') el.setAttribute('class', 'ref') el.setAttribute('href', linkPrefix + cls.HREF.xt(content)) textel = minidom.Text() textel.data = cls.ALL_TEXT.xt(content) el.appendChild(textel) p = p.replace(key, el.toxml()) return p
def _append_folder_to_dom(folder_name, dom): node = minidom.Element('file') node.setAttribute('type', 'folder') _append_child_tag(node, 'thumb', '') _append_child_tag(node, 'source', folder_name) _append_child_tag(node, 'description', folder_name) if _get_gallery_element(dom).firstChild: _get_gallery_element(dom).insertBefore( node, _get_gallery_element(dom).firstChild) else: _get_gallery_element(dom).appendChild(node)
def xmlElement(self): '''Creates an XML Dom Element for this Goal. Subclasses of Goal should call this to instantiate the node and then add their unique attributes. @returns An instnace of xml.minidom.Element containing this node's data ''' node = minidom.Element('Goal') node.setAttribute('type', self.TYPE) node.setAttribute('id', '%d' % self.id) node.setAttribute('weight', '{0:.{1}f}'.format(self.weight, DIGITS)) node.setAttribute('capacity', '%d' % self.capacity) return node
def test_setTitle(self): """ L{tree.setTitle} inserts the given title into the first I{title} element and the first element with the I{title} class in the given template. """ parent = dom.Element('div') firstTitle = dom.Element('title') parent.appendChild(firstTitle) secondTitle = dom.Element('span') secondTitle.setAttribute('class', 'title') parent.appendChild(secondTitle) titleNodes = [dom.Text()] # minidom has issues with cloning documentless-nodes. See Python issue # 4851. titleNodes[0].ownerDocument = dom.Document() titleNodes[0].data = 'foo bar' tree.setTitle(parent, titleNodes, None) self.assertEqual(firstTitle.toxml(), '<title>foo bar</title>') self.assertEqual(secondTitle.toxml(), '<span class="title">foo bar</span>')
def _elementConstructor(self, tag_name, namespaceURI=None, prefix=None, localName=None): element = DOM.Element(tag_name, namespaceURI, prefix, localName) prefix = self.getPrefix(tag_name) localName = self.getLocalName(tag_name) element.prefix = prefix element.localName = localName return element
def _toxml(self, dom): """ Return a XML Representation of the object """ element = minidom.Element(self.__xmlnodename__) for property, value in self.__dict__.iteritems(): if not property in self.__ignore__ and not inspect.isfunction(value): if property in self.__attribute_types__: if type(value) == list: node = minidom.Element(property) node.setAttribute('type', 'array') for v in value: child = v._toxml(dom) if child is not None: node.appendChild(child) element.appendChild(node) else: element.appendChild(value._toxml(dom)) else: node = minidom.Element(property) node_txt = dom.createTextNode(str(value).encode('ascii', 'xmlcharrefreplace')) node.appendChild(node_txt) element.appendChild(node) return element
def getProjectVersionElement(verFile, proj): try: proj = proj[proj.rfind('\\') + 1:] xml = dom.parse(verFile) elems = xml.getElementsByTagName('Version') if len(elems) > 0: verElem = elems.pop() element = dom.Element('Project') element.setAttribute('name', proj) element.appendChild(verElem) return element except: pass return None
def test_addPyListingsSkipLines(self): """ If a node with the I{py-listing} class also has a I{skipLines} attribute, that number of lines from the beginning of the source listing are omitted. """ listingPath = FilePath(self.mktemp()) listingPath.setContent('def foo():\n pass\n') parent = dom.Element('div') listing = dom.Element('a') listing.setAttribute('href', listingPath.basename()) listing.setAttribute('class', 'py-listing') listing.setAttribute('skipLines', 1) parent.appendChild(listing) tree.addPyListings(parent, listingPath.dirname()) expected = """\ <div><div class="py-listing"><pre><p class="py-linenumber">1 </p> <span class="py-src-keyword">pass</span> </pre><div class="caption"> - <a href="temp"><span class="filename">temp</span></a></div></div></div>""" self.assertEqual(parent.toxml(), expected)
def saveWorkflow(self, filename): try: document = minidom.getDOMImplementation().createDocument( None, "workflow", None) root = document.documentElement for module in self.modules: moduleElement = minidom.Element("module") moduleElement.setAttribute("filename", module.__module__ + ".py") for setting in module.settings.items(): if setting[1].value is not None: settingElement = minidom.Element("setting") settingElement.setAttribute("name", setting[0]) settingElement.setAttribute("value", str(setting[1].value)) moduleElement.appendChild(settingElement) root.appendChild(moduleElement) wflow = open(filename, "w") wflow.write(document.toprettyxml()) wflow.close() return True except Exception as e: promptService.alert(None, "Error", "Error saving module:\n" + str(e))
def toxml(self): xml = minidom.Document() queue = deque() queue.append((self, xml)) while queue: element, xml_node = queue.popleft() xml_element = minidom.Element(element.CurrentControlTypeName) xml_element.setAttribute('Name', str(element.CurrentName)) xml_element.setAttribute('AutomationId', str(element.CurrentAutomationId)) xml_element.setAttribute('ClassName', str(element.CurrentClassName)) xml_element.ownerDocument = xml xml_node.appendChild(xml_element) for child in element.findall('children'): queue.append((child, xml_element)) return xml.toprettyxml()
def test_nonASCIIData(self): """ A document which contains non-ascii characters is serialized to a file using UTF-8. """ document = dom.Document() parent = dom.Element('foo') text = dom.Text() text.data = u'\N{SNOWMAN}' parent.appendChild(text) document.appendChild(parent) outFile = self.mktemp() tree._writeDocument(outFile, document) self.assertXMLEqual( FilePath(outFile).getContent(), u'<foo>\N{SNOWMAN}</foo>'.encode('utf-8'))
def start_element_handler(self, name, attributes): if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) else: uri = EMPTY_NAMESPACE qname = name localname = None prefix = EMPTY_PREFIX node = minidom.Element(qname, uri, prefix, localname) node.ownerDocument = self.document _append_child(self.curNode, node) self.curNode = node if self._ns_ordered_prefixes: for prefix, uri in self._ns_ordered_prefixes: if prefix: a = minidom.Attr(_intern(self, 'xmlns:' + prefix), XMLNS_NAMESPACE, prefix, "xmlns") else: a = minidom.Attr("xmlns", XMLNS_NAMESPACE, "xmlns", EMPTY_PREFIX) a.value = uri a.ownerDocument = self.document _set_attribute_node(node, a) del self._ns_ordered_prefixes[:] if attributes: node._ensure_attributes() _attrs = node._attrs _attrsNS = node._attrsNS for i in range(0, len(attributes), 2): aname = attributes[i] value = attributes[i + 1] if ' ' in aname: uri, localname, prefix, qname = _parse_ns_name(self, aname) a = minidom.Attr(qname, uri, localname, prefix) _attrs[qname] = a _attrsNS[(uri, localname)] = a else: a = minidom.Attr(aname, EMPTY_NAMESPACE, aname, EMPTY_PREFIX) _attrs[aname] = a _attrsNS[(EMPTY_NAMESPACE, aname)] = a a.ownerDocument = self.document a.value = value a.ownerElement = node
def _createNode(doc, accessible, parentElement): e = minidom.Element("accessible") nameA = doc.createAttribute('name') roleA = doc.createAttribute('role') descA = doc.createAttribute('description') e.setAttributeNode(nameA) e.setAttributeNode(roleA) e.setAttributeNode(descA) e.setAttribute("name", accessible.name) e.setAttribute("role", str(int(accessible.getRole()))) e.setAttribute("description", accessible.description) for i in range(0, accessible.childCount): _createNode(doc, accessible.getChildAtIndex(i), e) parentElement.appendChild(e)
def removeH1(document): """ Replace all C{h1} nodes in the given document with empty C{span} nodes. C{h1} nodes mark up document sections and the output template is given an opportunity to present this information in a different way. @type document: A DOM Node or Document @param document: The input document which contains all of the content to be presented. @return: C{None} """ h1 = domhelpers.findNodesNamed(document, 'h1') empty = dom.Element('span') for node in h1: node.parentNode.replaceChild(empty, node)
def xmlElement(self): '''Creates an XML Dom Element for this GoalSet. @returns An instnace of minidom.Element containing this node's data. If there are no goals or unknown tags, it returns None. ''' root = None if (len(self.goals) or (self.robust and len(self.unknownTags))): root = minidom.Element('GoalSet') root.setAttribute('id', '%d' % (self.id)) ids = self.goals.keys() ids.sort() for id in ids: root.appendChild(self.goals[id].xmlElement()) if (self.robust): for tag in self.unknownTags: root.appendChild(tag) return root
def addItemToHistory(self, item: str) -> None: item = item.strip(" \n\t") itemNode = dom.Element("item") text = self.tree.createTextNode(item) # type: str itemNode.appendChild(text) # type: List[str] items = self.tree.getElementsByTagName("item") if len(items) >= self.maxSize: self.tree.firstChild.removeChild(items[-1]) self._removeLastItem() items = self.tree.getElementsByTagName("item") if not items: self.tree.firstChild.appendChild(itemNode) else: for n in items: if self._getText(n) == item: return self.tree.firstChild.insertBefore(itemNode, items[0]) self._insertItem(0, item)
def _create_metadata(node, exif): camera = _get_image_camera(exif) lens = _get_image_lens(exif) focal_length = _get_image_focal_length(exif) iso = _get_image_iso(exif) shutter_speed = _get_image_shutter_speed(exif) aperture = _get_image_aperture(exif) if not (camera or lens or focal_length or iso or shutter_speed or aperture): return meta = minidom.Element('meta') _append_child_tag(meta, 'camera', camera) _append_child_tag(meta, 'lens', lens) _append_child_tag(meta, 'focal_length', focal_length) _append_child_tag(meta, 'iso', iso) _append_child_tag(meta, 'shutter_speed', shutter_speed) _append_child_tag(meta, 'aperture', aperture) return meta