def save(self, oglObjects): """ Saves save diagram in XML file. TODO: Does not generate 'real' XMI Args: oglObjects: """ root = Document() top = Element("Pyut") root.appendChild(top) self.__savedLinks = {} # gauge dlg = wx.Dialog(None, -1, "Saving...", style=wx.STAY_ON_TOP | wx.CAPTION | wx.RESIZE_BORDER, size=wx.Size(207, 70)) gauge = wx.Gauge(dlg, -1, len(oglObjects), pos=wx.Point(2, 5), size=wx.Size(200, 30)) dlg.Show(True) for i in range(len(oglObjects)): gauge.SetValue(i) top.appendChild(self._oglClassToXml(oglObjects[i])) dlg.Destroy() self.__savedLinks = None return root
def xml_encode(self, text): from xml.dom.minidom import Text, Element t = Text() t.data = text e = Element('x') e.appendChild(t) return e.toxml()[3:-4]
def append_dict(doc: Document, element: Element, d: {}) -> None: # noinspection SpellCheckingInspection """ Appends a dictionary to the specified element in the xml document. This is a very trivial serialization of the dicts returned by the umapi queries :param doc: :param element: :param d: :return: """ for key, value in d.items(): if isinstance(value, str): append_info_element(doc, element, key, 'S', value) if isinstance(value, int): append_info_element(doc, element, key, 'I', str(value)) if isinstance(value, list): list_element = doc.createElement(key) for i in value: item = doc.createElement('item') text = doc.createTextNode(i) item.appendChild(text) list_element.appendChild(item) element.appendChild(list_element)
def _oglClassToXml(self, oglClass): """ Export an OglClass to a miniDom Element Args: oglClass: Returns: A minidom element """ root = Element('GraphicClass') # class definition # adding width and height w, h = oglClass.GetBoundingBoxMin() root.setAttribute('width', str(int(w))) root.setAttribute('height', str(int(h))) # calculate the top right corner of the shape x = int(oglClass.GetX()) y = int(oglClass.GetY()) root.setAttribute('x', str(int(x))) root.setAttribute('y', str(int(y))) # adding the class root.appendChild(self._pyutClassToXml(oglClass.getPyutClass())) return root
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>')
class MagicpointOutputTests(TestCase): """ Tests for L{lore.slides.MagicpointOutput}. """ def setUp(self): self.filename = self.mktemp() self.output = [] self.spitter = MagicpointOutput(self.output.append, filename=self.filename) self.parent = Element('html') title = Element('title') text = Text() text.data = "My Title" title.appendChild(text) self.body = Element('body') self.parent.appendChild(title) self.parent.appendChild(self.body) def test_body(self): """ L{MagicpointOutput.visitNode} emits a verbatim block when it encounters a I{body} element. """ link = Element('link') link.setAttribute('class', 'author') text = Text() text.data = u"John Doe" link.appendChild(text) self.body.appendChild(link) head = Element('h2') first = Text() first.data = u'My Header' head.appendChild(first) self.body.appendChild(head) self.spitter.visitNode(self.parent) self.assertEqual( ''.join(self.output), '%page\n\nMy Title\n\n\n%center\n\n\n\n\nJohn Doe\n%page\n\n' 'My Title\n\n\n\tMy Header\nJohn Doe%page\n\nMy Header\n\n\n') def test_pre(self): """ L{MagicpointOutput.visitNode} emits the 'typewriter' font when it encounters a I{pre} element. """ pre = Element('pre') text = Text() text.data = u"\nfirst line\nsecond line\n\n" pre.appendChild(text) self.body.appendChild(pre) self.spitter.visitNode(self.parent) self.assertEqual( ''.join(self.output), '%page\n\nMy Title\n\n\n%center\n\n\n\n\n%page\n\nMy Title\n\n\n' '%font "typewriter", size 4\n first line\n second line\n \n' '%font "standard"\n')
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 get(self, *args): self.response.headers['Content-Type'] = "application/rss+xml" items = self.getItems(*args) itemElems = [] for item in items: itemElem = Element("item") self._appendElementWithTextNode(itemElem, "title", item.title) self._appendElementWithTextNode(itemElem, "link", item.link) self._appendElementWithTextNode(itemElem, "description", item.description) self._appendElementWithTextNode(itemElem, "guid", item.link) if item.subPlaceFeedLink: self._appendElementWithTextNode(itemElem, "sharkattackdata:subPlaceFeedLink", item.subPlaceFeedLink) if item.attackFeedLink: self._appendElementWithTextNode(itemElem, "sharkattackdata:attackFeedLink", item.attackFeedLink) itemElems.append(itemElem) # Need to make channel element after the generator returned by getItems has been iterated. channelElem = Element("channel") self._appendElementWithTextNode(channelElem, "title", self._feedTitle) self._appendElementWithTextNode(channelElem, "link", self._feedLink) self._appendElementWithTextNode(channelElem, "description", self._feedDescription) for itemElem in itemElems: channelElem.appendChild(itemElem) responseText = """<?xml version="1.0"?> <rss version="2.0" xmlns:sharkattackdata="http://sharkattackdata.com/rss/modules/1.0/"> %s </rss> """ % (channelElem.toprettyxml()) self.response.out.write(responseText)
def _OglClass2xml(self, oglClass): """ Exporting an OglClass to an miniDom Element @since 2.0 @Deve Roux <*****@*****.**> @param oglClass @return Element """ root = Element('GraphicClass') # class definition # adding width and height w, h = oglClass.GetBoundingBoxMin() root.setAttribute('width', str(int(w))) root.setAttribute('height', str(int(h))) # calculate the top right corner of the shape x = int(oglClass.GetX()) y = int(oglClass.GetY()) root.setAttribute('x', str(int(x))) root.setAttribute('y', str(int(y))) # adding the class root.appendChild(self._PyutClass2xml(oglClass.getPyutClass())) return root
def elementAddChildNodes(srcNodes: [Node], dstDom: Document, dstElement: Element): """ 向element中添加child nodes :param srcNodes: 源nodes :param dstDom: 目标dom :param dstElement: 目标element """ lastNode: minidom.Node = None dstChildNodes = dstElement.childNodes if dstChildNodes: # 获取最后一个node lastNode = dstChildNodes[-1] for srcNode in srcNodes: newNode = DomXmlUtil.cloneNode(srcNode, dstDom) # 建立新的链表关系 if lastNode: lastNode.nextSibling = newNode newNode.previousSibling = lastNode else: newNode.previousSibling = None newNode.nextSibling = None lastNode = newNode # node添加进element dstElement.appendChild(newNode) pass
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 test_handleModelScreen(self, mock_handleWidgets): domDocument = Element('root') child = Element(u'widgets') domDocument.appendChild(child) childlist = [] childlist.append(child) handleModelScreen(domDocument, '') mock_handleWidgets.assert_has_call([mock.call(childlist)])
def test_handleOverrides(self, mock_handleWidgetOverrides): domDocument = Element('overrides') child = Element('widgets') domDocument.appendChild(child) handleOverrides([ domDocument, ]) mock_handleWidgetOverrides.assert_has_call([mock.call(child)])
def set_value_as_element(doc: Document, element: Element, name: str, value: Any): prop_element: Element = doc.createElement(name) if type(value) is dict: set_values_as_elements(doc, prop_element, value) else: set_element_value(prop_element, value) element.appendChild(prop_element)
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 test_hasoverride(self): domDocument = Element('test') child = Element('overrides') domDocument.appendChild(child) self.assertTrue(hasoverride(domDocument)) domDocument = Element('autre_test') child = Element('autre_child') domDocument.appendChild(child) self.assertFalse(hasoverride(domDocument))
def createNode(root, nodeName, nodeText): """ Add an element node with nodeText to the 'root' element """ from xml.dom.minidom import Element, Text ele = Element(nodeName) text = Text() text.data = nodeText ele.appendChild(text) root.appendChild(ele)
def appendChild(self, node): if hasattr(node, 'allowNoSvgChildNode'): if not self.allowAllSvgNodesAsChildNodes: if not (node.svgNodeType in self._allowedSvgChildNodes): raise HierarchyRequestErr("%s cannot be child of %s" % (repr(node), repr(self))) else: Element.appendChild(self, node) Element.appendChild(self, node)
def createNode(root, nodeName, nodeText): """ Add an element node with nodeText to the 'root' element """ from xml.dom.minidom import Element, Text ele = Element(nodeName) text = Text() text.data = nodeText ele.appendChild(text) root.appendChild(ele)
def add_addressBlock(self, parent: minidom.Element, node: AddressableNode) -> None: self._max_width = None addressBlock = self.doc.createElement(self.ns + "addressBlock") parent.appendChild(addressBlock) self.add_nameGroup(addressBlock, self.get_name(node), node.get_property("name", default=None), node.get_property("desc")) if (self.standard >= Standard.IEEE_1685_2014 ) and not node.get_property("ispresent"): self.add_value(addressBlock, self.ns + "isPresent", "0") self.add_value(addressBlock, self.ns + "baseAddress", self.hex_str(node.absolute_address)) # DNE: <spirit/ipxact:typeIdentifier> self.add_value(addressBlock, self.ns + "range", self.hex_str(node.size)) # RDL only encodes the bus-width at the register level, but IP-XACT # only encodes this at the addressBlock level! # Insert the width element for now, but leave contents blank until it is # determined later. # Exporter has no choice but to enforce a constant width throughout width_el = self.doc.createElement(self.ns + "width") addressBlock.appendChild(width_el) if isinstance(node, MemNode): self.add_value(addressBlock, self.ns + "usage", "memory") access = typemaps.access_from_sw(node.get_property("sw")) self.add_value(addressBlock, self.ns + "access", access) # DNE: <spirit/ipxact:volatile> # DNE: <spirit/ipxact:access> # DNE: <spirit/ipxact:parameters> self.add_registerData(addressBlock, node) # Width should be known by now # If mem, and width isn't known, check memwidth if isinstance(node, MemNode) and (self._max_width is None): self._max_width = node.get_property("memwidth") if self._max_width is not None: width_el.appendChild( self.doc.createTextNode("%d" % self._max_width)) else: width_el.appendChild(self.doc.createTextNode("32")) vendorExtensions = self.doc.createElement(self.ns + "vendorExtensions") self.addressBlock_vendorExtensions(vendorExtensions, node) if vendorExtensions.hasChildNodes(): addressBlock.appendChild(vendorExtensions)
def set_run_text(run: Element, text: str): dom = run.ownerDocument if run_contains_text(run): text_element = run.getElementsByTagNameNS(_namespaces['w'], 't')[0] set_text(text_element, text) else: text_element = dom.createElementNS(_namespaces['w'], 'w:t') set_text(text_element, text) run.appendChild(text_element)
def set_text(node: Element, text): dom = node.ownerDocument for child in node.childNodes: if child.nodeType == Node.TEXT_NODE: node.removeChild(child) text_node = dom.createTextNode(text) text_node.nodeValue = text node.appendChild(text_node)
def convertDictOrDocument(self, parent: minidom.Element, value: dict): self.setElementAttributes(parent, value) children = list(filter(lambda key: key[0] != "@" and key != "$value", value.keys())) if len(children) > 0: for key in children: element = self.document.createElement(key) self.convertValue(element, value[key]) parent.appendChild(element) else: parent.appendChild(self.document.createTextNode(str(value["$value"])))
def convertValue(self, parent: minidom.Element, value): if value is None: return elif isinstance(value, (list, set)): for item in value: self.convertValue(parent, item) elif isinstance(value, dict): self.convertDictOrDocument(parent, value) else: parent.appendChild(self.document.createTextNode(str(value)))
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 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 toDom(self): r = Element("enum") r.setAttribute("name",self.prefix[:-1]) if self.enumdict is None: return r for k in sorted(self.enumdict.keys()): i = Element("value") i.setAttribute("id",str(k)) i.setAttribute("name",self.enumdict[k]) r.appendChild(i) return r
def appendChild(self, node): if hasattr(node, 'allowNoSvgChildNode'): if not self.allowAllSvgNodesAsChildNodes: if not (node.svgNodeType in self._allowedSvgChildNodes): raise HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) else: Element.appendChild(self, node) Element.appendChild(self, node)
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 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 prepare_input(texts): records = Element('records') for text in texts: t = Text() t.data = text record = Element('record') record.appendChild(t) records.appendChild(record) return records.toxml()
def test_title(self): """ L{TexiSpitter.visitNode} emits I{@node} and I{@section} blocks when it encounters a I{title} element. """ titleElement = Element('title') text = Text() text.data = u'bar' titleElement.appendChild(text) self.spitter.visitNode(titleElement) self.assertEqual(''.join(self.output), '@node bar\n@section bar\n')
def test_code(self): """ L{TexiSpitter.visitNode} emits a C{@code} block when it encounters a I{code} element. """ codeElement = Element('code') text = Text() text.data = u'print' codeElement.appendChild(text) self.spitter.visitNode(codeElement) self.assertEqual(''.join(self.output), "@code{print}")
def test_code(self): """ L{TexiSpitter.visitNode} emits a C{@code} block when it encounters a I{code} element. """ codeElement = Element('code') text = Text() text.data = u'print' codeElement.appendChild(text) self.spitter.visitNode(codeElement) self.assertEqual(''.join(self.output), "@code{print}")
def _add_field(doc: Document, parent: Element, name: str, text: str, cdata: bool = False): el = doc.createElement(name) if cdata: txt = doc.createCDATASection(text) else: txt = doc.createTextNode(text) el.appendChild(txt) parent.appendChild(el)
def test_title(self): """ L{TexiSpitter.visitNode} emits I{@node} and I{@section} blocks when it encounters a I{title} element. """ titleElement = Element('title') text = Text() text.data = u'bar' titleElement.appendChild(text) self.spitter.visitNode(titleElement) self.assertEqual(''.join(self.output), '@node bar\n@section bar\n')
def test_pre(self): """ L{LatexSpitter.visitNode} emits a verbatim block when it encounters a I{pre} element. """ pre = Element('pre') text = Text() text.data = u"\n\n\nfoo\nbar\n\n\n" pre.appendChild(text) self.spitter.visitNode(pre) self.assertEqual(''.join(self.output), '\\begin{verbatim}\nfoo\nbar\n\\end{verbatim}\n')
def toXml(self, selected=None): doc = Document() doctype = DocumentType("Chapters") doctype.systemId = "matroskachapters.dtd" editions = Element("Chapters") for item in (selected or self): editions.appendChild(item.toXml()) doc.appendChild(doctype) doc.appendChild(editions) return doc
def test_pre(self): """ L{TexiSpitter.visitNode} emits a verbatim block when it encounters a I{pre} element. """ preElement = Element('pre') text = Text() text.data = u'foo' preElement.appendChild(text) self.spitter.visitNode(preElement) self.assertEqual(''.join(self.output), '@verbatim\nfoo\n@end verbatim\n')
def test_getLatexText(self): """ L{getLatexText} calls the writer function with all of the text at or beneath the given node. Non-ASCII characters are encoded using UTF-8. """ node = Element('foo') text = Text() text.data = u"foo \N{SNOWMAN}" node.appendChild(text) result = [] getLatexText(node, result.append) self.assertEqual(result, [u"foo \N{SNOWMAN}".encode('utf-8')])
def test_getLatexText(self): """ L{getLatexText} calls the writer function with all of the text at or beneath the given node. Non-ASCII characters are encoded using UTF-8. """ node = Element('foo') text = Text() text.data = u"foo \N{SNOWMAN}" node.appendChild(text) result = [] getLatexText(node, result.append) self.assertEqual(result, [u"foo \N{SNOWMAN}".encode('utf-8')])
def test_pre(self): """ L{TexiSpitter.visitNode} emits a verbatim block when it encounters a I{pre} element. """ preElement = Element('pre') text = Text() text.data = u'foo' preElement.appendChild(text) self.spitter.visitNode(preElement) self.assertEqual(''.join(self.output), '@verbatim\nfoo\n@end verbatim\n')
def test_pre(self): """ L{LatexSpitter.visitNode} emits a verbatim block when it encounters a I{pre} element. """ pre = Element('pre') text = Text() text.data = u"\n\n\nfoo\nbar\n\n\n" pre.appendChild(text) self.spitter.visitNode(pre) self.assertEqual( ''.join(self.output), '\\begin{verbatim}\nfoo\nbar\n\\end{verbatim}\n')
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 buildBody(self, attributes={}, child=None): body = Element('body') body.setAttribute('xmlns', NS_HTTPBIND) body.setAttribute('rid', str(self.rid)) body.setAttribute('xml:lang', 'en') if self.sid: body.setAttribute('sid', self.sid) for attribute in attributes: body.setAttribute(attribute, attributes[attribute]) if child is not None: body.appendChild(child) self.rid = self.rid + 1 return body
def setUp(self): self.filename = self.mktemp() self.output = [] self.spitter = MagicpointOutput(self.output.append, filename=self.filename) self.parent = Element('html') title = Element('title') text = Text() text.data = "My Title" title.appendChild(text) self.body = Element('body') self.parent.appendChild(title) self.parent.appendChild(self.body)
def bindResource(self): body = self.buildBody(attributes={ 'xmpp:restart': 'true', 'xmlns:xmpp': 'urn:xmpp:xbosh'}) response = self.sendRequest(body) if not response: return False if not response.getElementsByTagName('bind'): return False dom = Document() iq = Element('iq') iq.setAttribute('id', str(random.randint(0, 1000000))) iq.setAttribute('type', 'set') bind = Element('bind') bind.setAttribute('xmlns', NS_BIND) resource = Element('resource') resource_str = dom.createTextNode(self.jid.resource) resource.appendChild(resource_str) bind.appendChild(resource) iq.appendChild(bind) body = self.buildBody(child=iq) response = self.sendRequest(body) if not response or not response.getElementsByTagName('jid'): return False iq = Element('iq') iq.setAttribute('id', str(random.randint(0, 1000000))) iq.setAttribute('type', 'set') session = Element('session') session.setAttribute('xmlns', NS_SESSION) iq.appendChild(session) body = self.buildBody(child=iq) response = self.sendRequest(body) return True
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 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 test_code(self): """ L{LatexSpitter.visitNode} emits a C{texttt} block when it encounters a I{code} element and inserts optional linebreaks at sensible places in absolute python names. """ code = Element('code') text = Text() text.data = u"print this: twisted.lore.latex" code.appendChild(text) self.spitter.visitNode(code) self.assertEqual( ''.join(self.output), "\\texttt{print this: twisted.\\linebreak[1]lore.\\" "linebreak[1]latex}")
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 _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 test_pre(self): """ L{MagicpointOutput.visitNode} emits the 'typewriter' font when it encounters a I{pre} element. """ pre = Element('pre') text = Text() text.data = u"\nfirst line\nsecond line\n\n" pre.appendChild(text) self.body.appendChild(pre) self.spitter.visitNode(self.parent) self.assertEqual( ''.join(self.output), '%page\n\nMy Title\n\n\n%center\n\n\n\n\n%page\n\nMy Title\n\n\n' '%font "typewriter", size 4\n first line\n second line\n \n' '%font "standard"\n')
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_li(self): """ L{DocbookSpitter} wraps any non-I{p} elements found intside any I{li} elements with I{p} elements. """ output = [] spitter = DocbookSpitter(output.append) li = Element('li') li.appendChild(Element('p')) text = Text() text.data = 'foo bar' li.appendChild(text) spitter.visitNode(li) self.assertEqual( ''.join(output), '<listitem><para></para><para>foo bar</para></listitem>')
class FamilyElement(Element): def __init__(self, name): Element.__init__(self, 'family') self.setAttribute('name', name) self.parents = Element('parents') self.environ = Element('environ') self.appendChild(self.parents) self.appendChild(self.environ) def append_parents(self, parents): for parent in parents: pelement = TextElement('parent', parent) #pelement.setAttribute('ord', str(trait.ord)) self.parents.appendChild(pelement) def append_variables(self, rows): for row in rows: velement = FamilyVariableElement(row.trait, row.name, row.value) self.environ.appendChild(velement)
class ProfileElement(Element): def __init__(self, name, suite): Element.__init__(self, "profile") self.setAttribute("name", name) self.setAttribute("suite", suite) self.traits = Element("traits") self.appendChild(self.traits) self.environ = Element("environ") self.appendChild(self.environ) def append_traits(self, trait_rows): for trait in trait_rows: telement = TextElement("trait", trait.trait) telement.setAttribute("ord", str(trait.ord)) self.traits.appendChild(telement) def append_variables(self, rows): for row in rows: velement = ProfileVariableElement(row.trait, row.name, row.value) self.environ.appendChild(velement)