def test_insertPrevNextText(self): """ L{insertPrevNextLinks} appends a text node with the title of the previous slide to each node with a I{previous} class and the title of the next slide to each node with a I{next} class. """ next = Element('span') next.setAttribute('class', 'next') container = Element('div') container.appendChild(next) slideWithNext = HTMLSlide(container, 'first', 0) previous = Element('span') previous.setAttribute('class', 'previous') container = Element('div') container.appendChild(previous) slideWithPrevious = HTMLSlide(container, 'second', 1) insertPrevNextLinks( [slideWithNext, slideWithPrevious], None, None) self.assertEqual( next.toxml(), '<span class="next">second</span>') self.assertEqual( previous.toxml(), '<span class="previous">first</span>')
def _add_lang_to_html(htmltext, lang): ''' Take a piece of HTML and add an xml:lang attribute to it. ''' if lang == 'und': return htmltext parser = html5lib.HTMLParser( tree=html5lib.treebuilders.getTreeBuilder("dom") ) html = parser.parseFragment(htmltext) html.normalize() if len(html.childNodes) == 0: return '<div xml:lang="%s"></div>' % lang elif len(html.childNodes) == 1: node = html.firstChild if node.nodeType == Node.TEXT_NODE: div = Element('div') div.ownerDocument = html div.setAttribute('xml:lang', lang) div.childNodes = [node] html.childNodes = [div] else: node.setAttribute('xml:lang', lang) else: #add a single encompassing div div = Element('div') div.ownerDocument = html div.setAttribute('xml:lang', lang) div.childNodes = html.childNodes html.childNodes = [div] return html.toxml()
def create_clipitem_from_playlist_entry(k, e, properties, e_in, e_out, playlist_current_frame): global clip_id """ Creates clipitem element. The subelements common to both audio and video clipitem (that is : name, duration, rate, in, out, start, end) are included """ e_len = e_out - e_in o_clipitem = Element("clipitem") resource = get_property(properties, "resource") print resource length = get_property(properties, "length") resource_base_name = str(os.path.basename(resource)) o_clipitem.setAttribute("id", resource_base_name + "_" + str(clip_id)) clip_id = clip_id + 1 print resource_base_name o_clipitem.appendChild(create_simple_element("name", resource_base_name)) o_clipitem.appendChild(create_simple_element("duration", length)) o_clipitem.appendChild(create_rate()) o_clipitem.appendChild(create_simple_element("in", str(e_in))) o_clipitem.appendChild(create_simple_element("out", str(e_out))) o_clipitem.appendChild( create_simple_element("start", str(playlist_current_frame))) o_clipitem.appendChild( create_simple_element("end", str(playlist_current_frame + e_len))) return o_clipitem
def add_lang_to_html(htmltext, lang): ''' Take a piece of HTML and add an xml:lang attribute to it. .. versionadded:: 0.7.0 ''' if lang == 'und': return htmltext parser = html5lib.HTMLParser( tree=html5lib.treebuilders.getTreeBuilder("dom") ) html = parser.parseFragment(htmltext) html.normalize() if len(html.childNodes) == 0: return '<div xml:lang="%s"></div>' % lang elif len(html.childNodes) == 1: node = html.firstChild if node.nodeType == Node.TEXT_NODE: div = Element('div') div.ownerDocument = html div.setAttribute('xml:lang', lang) div.childNodes = [node] html.childNodes = [div] else: node.setAttribute('xml:lang', lang) else: #add a single encompassing div div = Element('div') div.ownerDocument = html div.setAttribute('xml:lang', lang) div.childNodes = html.childNodes html.childNodes = [div] return html.toxml()
def test_insertImages(self): """ L{formulaeToImages} replaces any elements with the I{latexformula} class with I{img} elements which refer to external images generated based on the latex in the original elements. """ parent = Element('div') base = FilePath(self.mktemp()) base.makedirs() macros = Element('span') macros.setAttribute('class', 'latexmacros') text = Text() text.data = 'foo' macros.appendChild(text) parent.appendChild(macros) formula = Element('span') formula.setAttribute('class', 'latexformula') text = Text() text.data = 'bar' formula.appendChild(text) parent.appendChild(formula) # Avoid actually executing the commands to generate images from the # latex. It might be nice to have some assertions about what commands # are executed, or perhaps even execute them and make sure an image # file is created, but that is a task for another day. commands = [] formulaeToImages(parent, base.path, _system=commands.append) self.assertEqual( parent.toxml(), '<div><span><br/><img src="latexformula0.png"/><br/></span></div>')
def test_insertPrevNextText(self): """ L{insertPrevNextLinks} appends a text node with the title of the previous slide to each node with a I{previous} class and the title of the next slide to each node with a I{next} class. """ next = Element('span') next.setAttribute('class', 'next') container = Element('div') container.appendChild(next) slideWithNext = HTMLSlide(container, 'first', 0) previous = Element('span') previous.setAttribute('class', 'previous') container = Element('div') container.appendChild(previous) slideWithPrevious = HTMLSlide(container, 'second', 1) insertPrevNextLinks( [slideWithNext, slideWithPrevious], None, None) self.assertEqual( next.toxml(), '<span class="next">second</span>') self.assertEqual( previous.toxml(), '<span class="previous">first</span>')
def test_insertImages(self): """ L{formulaeToImages} replaces any elements with the I{latexformula} class with I{img} elements which refer to external images generated based on the latex in the original elements. """ parent = Element('div') base = FilePath(self.mktemp()) base.makedirs() macros = Element('span') macros.setAttribute('class', 'latexmacros') text = Text() text.data = 'foo' macros.appendChild(text) parent.appendChild(macros) formula = Element('span') formula.setAttribute('class', 'latexformula') text = Text() text.data = 'bar' formula.appendChild(text) parent.appendChild(formula) # Avoid actually executing the commands to generate images from the # latex. It might be nice to have some assertions about what commands # are executed, or perhaps even execute them and make sure an image # file is created, but that is a task for another day. commands = [] formulaeToImages(parent, base.path, _system=commands.append) self.assertEqual( parent.toxml(), '<div><span><br/><img src="latexformula0.png"/><br/></span></div>')
def get_file_entry(resource,clip_len,properties): resource_base_name = str(os.path.basename(resource)) fn = resource_base_name.split(".")[0] o_file = Element("file") o_file.setAttribute("id", fn) if not used_files.has_key(resource_base_name): used_files[resource_base_name]=resource # here add info of file # o_file.appendChild(create_simple_element("name", clip_resource_basename)) o_file.appendChild(create_simple_element("name", resource_base_name)) o_pathurl=create_simple_element("pathurl", resource) o_file.appendChild(o_pathurl) o_rate=Element("rate") o_rate.appendChild(create_simple_element("timebase", "25")) o_file.appendChild(o_rate) o_file.appendChild(create_simple_element("duration", str(clip_len))) o_file_media = Element("media") video_index=get_property(properties, "video_index") if int(video_index)>=0: o_file_media_video = Element("video") o_file_media_video.appendChild(create_simple_element("duration", str(clip_len))) o_file_media.appendChild(o_file_media_video) num_audio_channels=producer_get_audio_channels_from_properties(properties) if int(num_audio_channels)>0: o_file_media_audio = Element("audio") [sample_rate, depth] = get_audio_params_from_properties(properties) o_samplecharacteristics = Element("samplecharacteristics") o_samplecharacteristics.appendChild(create_simple_element("samplerate", str(sample_rate))) o_samplecharacteristics.appendChild(create_simple_element("depth", str(depth))) o_file_media_audio.appendChild(o_samplecharacteristics) o_file_media_audio_channelcount = create_simple_element("channelcount", num_audio_channels) o_file_media_audio.appendChild(o_file_media_audio_channelcount) o_file_media.appendChild(o_file_media_audio) o_file.appendChild(o_file_media) return o_file
def _getElementForMappingEntry(entry, mappingStyle): e = Element(mappingStyle) for k, v in entry.items(): # ignore empty, None or compiled regexp items into output if not v or (k == "path-match-expr"): continue e.setAttribute(k, str(v)) return e
def _pyutClassCommonToXml(self, classCommon: PyutClassCommon, root: Element) -> Element: root.setAttribute(PyutXmlConstants.ATTR_DESCRIPTION, classCommon.description) # root.setAttribute(PyutXmlConstants.ATTR_FILENAME, pyutInterface.getFilename()) return root
def _getElementForMappingEntry(entry, mappingStyle): e = Element(mappingStyle) for k, v in entry.items(): # ignore empty, None or compiled regexp items into output if not v or (k == "path-match-expr"): continue e.setAttribute(k, str(v)) return e
def node2xml(node): """Takes in a node object and returns an XML object for that node""" ele = Element('node') for k, v in node.attrs.items(): ele.setAttribute(k, v) for k, v in node.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def to_xml(self, obj, parent: minidom.Element, dom: minidom.Document): value = getattr(obj, self.att_name) if value is not None: if isinstance(value, ValueReference): xml_str = ":" + value.id else: xml_str = value_to_xml_string(value, self.type) parent.setAttribute(self.name, xml_str)
def set_scripts(self): self.scripts = [x.script for x in self.traitscripts.scripts(self.name)] while self.scripts_element.hasChildNodes(): del self.scripts_element.childNodes[0] for script in self.scripts: element = Element('script') element.setAttribute('name', script) self.scripts_element.appendChild(element)
def set_scripts(self): self.scripts = [x.script for x in self.traitscripts.scripts(self.name)] while self.scripts_element.hasChildNodes(): del self.scripts_element.childNodes[0] for script in self.scripts: element = Element('script') element.setAttribute('name', script) self.scripts_element.appendChild(element)
def test_attribute2param(self): element = Element('cbrun') element.setAttribute('href', 'http://site.free.fr') element.setAttribute('style', 'bien') self.assertItemsEqual(attribute2param(element), { 'href': 'http://site.free.fr', 'style': 'bien' })
def node2xml(node): """Takes in a node object and returns an XML object for that node""" ele = Element("node") for k, v in node.attrs.items(): ele.setAttribute(k, v) for k, v in node.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def fetch(self, output_directory='none'): element = Element('Water_meter001') element.setAttribute('Meter_Reading','%f' % self._data) self.output_directory.write("\r\n") self.output_directory.write(element.toxml()) #element.toxml() pass
def parse_xml(text: xml.Element) -> template.Node: """ Parses a dom element in the spdx-license-XML format and returns a Node. """ transformer = _XmlTransformer() text.setAttribute('spacing', 'none') tree = transformer.transform_node(text) tree = tree.simplify() return tree
def to_dom(self): root_node = Element("root", namespaceURI=NAMESPACE) root_node.setAttribute("str", self.str) root_node.setAttribute("lemma", self.lemma) root_node.setAttribute("lemma_root", self.lemma_root) root_node.setAttribute("syntactic_category", self.syntactic_category) if self.secondary_syntactic_category: root_node.setAttribute("secondary_syntactic_category", self.secondary_syntactic_category) return root_node
def test_anchorRef(self): """ L{LatexSpitter.visitNode} emits a footnote when it encounters an I{a} element with an I{href} attribute with a network scheme. """ listing = Element('a') listing.setAttribute('href', 'http://example.com/foo') self.spitter.visitNode(listing) self.assertEqual(''.join(self.output), "\\footnote{http://example.com/foo}")
def fetch(self, output_directory): ''' The output_directory parameter is ignored. ''' formatted_datetime = self._captured_datetime.strftime(self._format) element = Element('DateTime') element.setAttribute('CurrentDateTime', formatted_datetime) return element
def to_dom(self): root_node = Element("root", namespaceURI=NAMESPACE) root_node.setAttribute("str", self.str) root_node.setAttribute("lemma", self.lemma) root_node.setAttribute("lemma_root", self.lemma_root) root_node.setAttribute("syntactic_category", self.syntactic_category) if self.secondary_syntactic_category: root_node.setAttribute("secondary_syntactic_category", self.secondary_syntactic_category) return root_node
def way2xml(way): ele = Element('way') for k, v in way.attrs.items(): ele.setAttribute(k, v) for ref in way.nodes: nd = Element('nd') nd.setAttribute('ref', ref) ele.appendChild(nd) for k, v in way.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def way2xml(way): ele = Element('way') for k,v in way.attrs.items(): ele.setAttribute(k,v) for ref in way.nodes: nd = Element('nd') nd.setAtrribute('ref', ref) ele.appendChild(nd) for k,v in way.tags.items(): ele.appendChild(tags2xml(k,v)) return ele
def way2xml(way): ele = Element("way") for k, v in way.attrs.items(): ele.setAttribute(k, v) for ref in way.nodes: nd = Element("nd") nd.setAttribute("ref", ref) ele.appendChild(nd) for k, v in way.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def relation2xml(relation): ele = Element('relation') for k, v in relation.attrs.items(): ele.setAttribute(k, v) for member in relation.members: ele = Element('member') for k, v in member.items(): ele.setAttribute(k, v) for k, v in relation.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def relation2xml(relation): ele = Element("relation") for k, v in relation.attrs.items(): ele.setAttribute(k, v) for member in relation.members: ele = Element("member") for k, v in member.items(): ele.setAttribute(k, v) for k, v in relation.tags.items(): ele.appendChild(tag2xml(k, v)) return ele
def test_anchorName(self): """ When passed an I{a} element with a I{name} attribute, L{LatexSpitter.visitNode} emits a label. """ listing = Element('a') listing.setAttribute('name', 'foo') self.spitter.visitNode(listing) self.assertEqual( ''.join(self.output), "\\label{%sHASHfoo}" % (os.path.abspath(self.filename).replace('\\', '/'), ))
def edit_fill(element: Element, fill_color: str) -> None: """Change fill in element. Usaly wrapped in partial with fixed element.""" style = element.getAttribute('style') new_style = [] for css in style.split(';'): term, value = [v.strip() for v in css.split(':')] if term == 'fill': new_style.append('{}:{}'.format(term, fill_color)) else: new_style.append(css) element.setAttribute('style', ';'.join(new_style))
def test_anchorRef(self): """ L{LatexSpitter.visitNode} emits a footnote when it encounters an I{a} element with an I{href} attribute with a network scheme. """ listing = Element('a') listing.setAttribute('href', 'http://example.com/foo') self.spitter.visitNode(listing) self.assertEqual( ''.join(self.output), "\\footnote{http://example.com/foo}")
def sanitise_ids(node:Element) -> Element: if node.attributes and 'id' in node.attributes.keys(): original_name:str = node.getAttribute('id') sanitised_id:str = original_name i:int = 1 while sanitised_id in data.objects: i += 1 sanitised_id = original_name + '-' + str(i) node.setAttribute('id', sanitised_id) for child in node.childNodes: sanitise_ids(child) return node
def __init__(self, conn, suite): Element.__init__(self, 'traits') self.conn = conn self.suite = suite self.setAttribute('suite', self.suite) self._traits_ = StatementCursor(self.conn, 'Traits') self._traits_.set_table(ujoin(self.suite, 'traits')) self.traitnames = [row.trait for row in self._traits_.select(order='trait')] for t in self.traitnames: t_element = Element('trait') t_element.setAttribute('name', t) self.appendChild(t_element)
def __init__(self, conn, suite): Element.__init__(self, 'traits') self.conn = conn self.suite = suite self.setAttribute('suite', self.suite) self._traits_ = StatementCursor(self.conn, 'Traits') self._traits_.set_table(ujoin(self.suite, 'traits')) self.traitnames = [row.trait for row in self._traits_.select(order='trait')] for t in self.traitnames: t_element = Element('trait') t_element.setAttribute('name', t) self.appendChild(t_element)
def test_anchorName(self): """ When passed an I{a} element with a I{name} attribute, L{LatexSpitter.visitNode} emits a label. """ listing = Element('a') listing.setAttribute('name', 'foo') self.spitter.visitNode(listing) self.assertEqual( ''.join(self.output), "\\label{%sHASHfoo}" % ( os.path.abspath(self.filename).replace('\\', '/'),))
def __init__(self, conn, machines=None): Element.__init__(self, 'machines') self.conn = conn self.cursor = StatementCursor(self.conn) if machines is None: rows = self.cursor.select(table='machines', order='machine') machines = [r.machine for r in rows] self.machines = [] for machine in machines: machine_element = Element('machine') machine_element.setAttribute('name', machine) self.machines.append(machine_element) self.appendChild(machine_element)
def __init__(self, conn, machines=None): Element.__init__(self, 'machines') self.conn = conn self.cursor = StatementCursor(self.conn) if machines is None: rows = self.cursor.select(table='machines', order='machine') machines = [r.machine for r in rows] self.machines = [] for machine in machines: machine_element = Element('machine') machine_element.setAttribute('name', machine) self.machines.append(machine_element) self.appendChild(machine_element)
def test_add_orcids(self): """ According to "Tag by Tag The Elsevier DTD 5 Family of XML DTDs" orcids will be distributed as an attribute in the ce:author tag. """ xml_author = Element('ce:author') xml_author.setAttribute('orcid' , '1234-5678-4321-8765') authors = [{}] # _add_orcids will alter the authors list self.els._add_orcids(authors, [xml_author]) self.assertEqual(authors, [{'orcid': 'ORCID:1234-5678-4321-8765'}])
def to_xml(self, obj, parent: minidom.Element, dom: minidom.Document, type: TypeDescriptor = None): value = getattr(obj, self.att_name) if isinstance(value, SifValue) and isinstance(value.value, ValueReference): parent.setAttribute(self.name, ":" + value.value.id) return param = parent.appendChild(dom.createElement(self.name)) param.appendChild(value.to_dom(dom, self.type_for(type))) return param
def _create_failure_or_error(self, document, test, element_type): element = Element(element_type) element.setAttribute('type', self._get_attr(test, 'fail_class')) element.setAttribute('message', self._get_attr(test, 'fail_reason')) traceback_content = self._escape_cdata(test.get('traceback', self.UNKNOWN)) traceback = document.createCDATASection(traceback_content) element.appendChild(traceback) system_out = Element('system-out') system_out_cdata_content = self._escape_cdata(test.get('text_output', self.UNKNOWN)) system_out_cdata = document.createCDATASection(system_out_cdata_content) system_out.appendChild(system_out_cdata) element.appendChild(system_out) return element
def __init__(self, conn, mtypes=None): Element.__init__(self, "machine_types") self.conn = conn self.cursor = StatementCursor(self.conn) if mtypes is None: rows = self.cursor.select(table="machine_types", order="machine_type") mtypes = [r.machine_type for r in rows] self.machine_types = [] for mtype in mtypes: mtype_element = Element("machine_type") mtype_element.setAttribute("name", mtype) # mtype_element = MachineTypeElement(conn, mtype) self.machine_types.append(mtype_element) self.appendChild(mtype_element)
def test_add_orcids(self): """Test that orcids are good. According to "Tag by Tag The Elsevier DTD 5 Family of XML DTDs" orcids will be distributed as an attribute in the ce:author tag. """ xml_author = Element('ce:author') xml_author.setAttribute('orcid', '1234-5678-4321-8765') authors = [{}] # _add_orcids will alter the authors list self.els._add_orcids(authors, [xml_author]) self.assertEqual(authors, [{'orcid': 'ORCID:1234-5678-4321-8765'}])
def node(*args, **kwargs): """ args[0] -- a XML tag args[1:] -- an array of children to append to the newly created node or if a unicode arg is supplied it will be used to make a text node kwargs -- attributes returns a xml.dom.minidom.Element """ blocked_attributes = ['tag'] tag = args[0] if len(args) > 0 else kwargs['tag'] args = args[1:] result = Element(tag) unicode_args = [u for u in args if type(u) == unicode] assert len(unicode_args) <= 1 parsedString = False # kwargs is an xml attribute dictionary, # here we convert it to a xml.dom.minidom.Element for k, v in kwargs.iteritems(): if k in blocked_attributes: continue if k == 'toParseString': if v is True and len(unicode_args) == 1: parsedString = True # Add this header string so parseString can be used? s = u'<?xml version="1.0" ?><'+tag+'>' + unicode_args[0]\ + u'</'+tag+'>' node = parseString(s.encode("utf-8")).documentElement # Move node's children to the result Element # discarding node's root for child in node.childNodes: result.appendChild(copy.deepcopy(child)) else: result.setAttribute(k, v) if len(unicode_args) == 1 and not parsedString: text_node = Text() text_node.data = unicode_args[0] result.appendChild(text_node) for n in args: if type(n) == int or type(n) == float or type(n) == str: text_node = Text() text_node.data = unicode(n) result.appendChild(text_node) elif type(n) is not unicode: try: result.appendChild(n) except: raise Exception(type(n), n) return result
def node(*args, **kwargs): """ args[0] -- a XML tag args[1:] -- an array of children to append to the newly created node or if a unicode arg is supplied it will be used to make a text node kwargs -- attributes returns a xml.dom.minidom.Element """ blocked_attributes = ['tag'] tag = args[0] if len(args) > 0 else kwargs['tag'] args = args[1:] result = Element(tag) unicode_args = [u for u in args if type(u) == unicode] assert len(unicode_args) <= 1 parsedString = False # kwargs is an xml attribute dictionary, # here we convert it to a xml.dom.minidom.Element for k, v in kwargs.iteritems(): if k in blocked_attributes: continue if k == 'toParseString': if v is True and len(unicode_args) == 1: parsedString = True # Add this header string so parseString can be used? s = u'<?xml version="1.0" ?><'+tag+'>' + unicode_args[0]\ + u'</'+tag+'>' node = parseString(s.encode("utf-8")).documentElement # Move node's children to the result Element # discarding node's root for child in node.childNodes: result.appendChild(copy.deepcopy(child)) else: result.setAttribute(k, v) if len(unicode_args) == 1 and not parsedString: text_node = Text() text_node.data = unicode_args[0] result.appendChild(text_node) for n in args: if type(n) == int or type(n) == float or type(n) == str: text_node = Text() text_node.data = unicode(n) result.appendChild(text_node) elif type(n) is not unicode: try: result.appendChild(n) except: raise Exception(type(n), n) return result
def toDom(self): r = Element("phase") r.setAttribute("name",self._name) for n in self.variables.keys(): i = registry.getVariableById(n).getName() g=Element("variable") g.setAttribute("id",str(i)) if i in self.accounts: g.setAttribute("account","true") if i in self.inputs: g.setAttribute("input","true") if i in self.outputs: g.setAttribute("output","true") r.appendChild(g) return r
def render_GET(self, request): """ Render as HTML a listing of all known users with links to their personal resources. """ listing = Element('ul') for link, text in self._users(): linkElement = Element('a') linkElement.setAttribute('href', link + '/') textNode = Text() textNode.data = text linkElement.appendChild(textNode) item = Element('li') item.appendChild(linkElement) listing.appendChild(item) return self.template % {'users': listing.toxml()}
def render(self, request): """ Render as HTML a listing of all known users with links to their personal resources. """ listing = Element("ul") for link, text in self._users(): linkElement = Element("a") linkElement.setAttribute("href", link + "/") textNode = Text() textNode.data = text linkElement.appendChild(textNode) item = Element("li") item.appendChild(linkElement) listing.appendChild(item) return self.template % {"users": listing.toxml()}
def test_anchorListing(self): """ L{LatexSpitter.visitNode} emits a verbatim block when it encounters a code listing (represented by an I{a} element with a I{listing} class). """ path = FilePath(self.mktemp()) path.setContent('foo\nbar\n') listing = Element('a') listing.setAttribute('class', 'listing') listing.setAttribute('href', path.path) self.spitter.visitNode(listing) self.assertEqual( ''.join(self.output), "\\begin{verbatim}\n" "foo\n" "bar\n" "\\end{verbatim}\\parbox[b]{\\linewidth}{\\begin{center} --- " "\\begin{em}temp\\end{em}\\end{center}}")
def _create_failure_or_error(self, document, test, element_type): element = Element(element_type) element.setAttribute('type', self._get_attr(test, 'fail_class')) element.setAttribute('message', self._get_attr(test, 'fail_reason')) traceback_content = self._escape_cdata(test.get('traceback', self.UNKNOWN)) traceback = document.createCDATASection(traceback_content) element.appendChild(traceback) system_out = Element('system-out') try: with open(test.get("logfile"), "r") as logfile_obj: text_output = logfile_obj.read() except (TypeError, IOError): text_output = self.UNKNOWN system_out_cdata_content = self._escape_cdata(text_output) system_out_cdata = document.createCDATASection(system_out_cdata_content) system_out.appendChild(system_out_cdata) return element, system_out
def node(tag, *args, **kwargs): result = Element(tag) for k, v in kwargs.iteritems(): result.setAttribute(k, v) unicode_args = [u for u in args if type(u) == unicode] assert len(unicode_args) <= 1 if len(unicode_args) == 1: text_node = Text() text_node.data = unicode_args[0] result.appendChild(text_node) for n in args: if type(n) != unicode: try: result.appendChild(n) except: raise Exception(type(n), n) return result
def node(tag, *args, **kwargs): result = Element(tag) for k, v in kwargs.iteritems(): result.setAttribute(k, v) unicode_args = [u for u in args if type(u)==unicode] assert len(unicode_args)<=1 if len(unicode_args)==1: text_node = Text() text_node.data = unicode_args[0] result.appendChild(text_node) for n in args: if type(n)!=unicode: try: result.appendChild(n) except: raise Exception(type(n), n) return result
def _PyutField2xml(self, pyutField): """ Exporting an PyutField to an miniDom Element @param pyutField @return Element """ root = Element('Field') # adding the parent XML # pyutField is a param root.appendChild(self._PyutParam2xml(pyutField)) # field visibility root.setAttribute('visibility', str(pyutField.getVisibility())) return root
def __setitem__(self, tag, value): if value is None: return child = Element(tounicode(tag)) if isinstance(value, basestring): text = Text() text.data = tounicode(value) child.appendChild(text) elif isinstance(value, dict): for key, val in value.items(): child.setAttribute(tounicode(key), tounicode(val)) else: raise Exception("Ohno! I didn't expect %r" %(value, )) self.appendChild(child)
def __setitem__(self, tag, value): if value is None: return child = Element(tounicode(tag)) if isinstance(value, basestring): text = Text() text.data = tounicode(value) child.appendChild(text) elif isinstance(value, dict): for key, val in value.items(): child.setAttribute(tounicode(key), tounicode(val)) else: raise Exception("Ohno! I didn't expect %r" %(value, )) self.appendChild(child)
def test_anchorListing(self): """ L{LatexSpitter.visitNode} emits a verbatim block when it encounters a code listing (represented by an I{a} element with a I{listing} class). """ path = FilePath(self.mktemp()) path.setContent('foo\nbar\n') listing = Element('a') listing.setAttribute('class', 'listing') listing.setAttribute('href', path.path) self.spitter.visitNode(listing) self.assertEqual( ''.join(self.output), "\\begin{verbatim}\n" "foo\n" "bar\n" "\\end{verbatim}\\parbox[b]{\\linewidth}{\\begin{center} --- " "\\begin{em}temp\\end{em}\\end{center}}")
def _create_failure_or_error(self, document, test, element_type): element = Element(element_type) element.setAttribute('type', self._get_attr(test, 'fail_class')) element.setAttribute('message', self._get_attr(test, 'fail_reason')) traceback_content = self._escape_cdata( test.get('traceback', self.UNKNOWN)) traceback = document.createCDATASection(traceback_content) element.appendChild(traceback) system_out = Element('system-out') try: with open(test.get("logfile"), "r") as logfile_obj: text_output = logfile_obj.read() except (TypeError, IOError): text_output = self.UNKNOWN system_out_cdata_content = self._escape_cdata(text_output) system_out_cdata = document.createCDATASection( system_out_cdata_content) system_out.appendChild(system_out_cdata) return element, system_out
def test02(self): wsjrssall = open("wsjallfullrss.xml", "r") rssxml = wsjrssall.read() xml_doc = xml.dom.minidom.parseString(rssxml) print xml_doc.getElementsByTagName("channel") channel = xml_doc.getElementsByTagName("channel")[0] # print channel.childNodes # print channel.getElementsByTagName('link') for l in channel.getElementsByTagName("link"): if l in channel.childNodes: ognl_link = l break link = Element("link") link.setAttribute("href", "http://pubsubhubbub.appspot.com") link.setAttribute("rel", "hub") channel.insertBefore(link, ognl_link.nextSibling) # print xml_doc.toxml() pass
def test02(self): wsjrssall = open('wsjallfullrss.xml', 'r') rssxml = wsjrssall.read() xml_doc = xml.dom.minidom.parseString(rssxml) print xml_doc.getElementsByTagName('channel') channel = xml_doc.getElementsByTagName('channel')[0] #print channel.childNodes #print channel.getElementsByTagName('link') for l in channel.getElementsByTagName('link'): if l in channel.childNodes: ognl_link = l break link = Element('link') link.setAttribute('href', 'http://pubsubhubbub.appspot.com') link.setAttribute('rel', 'hub') channel.insertBefore(link, ognl_link.nextSibling) #print xml_doc.toxml() pass