def toXml(self): xml = Element("ChapterAtom") subtag = Element("ChapterUID") text = Text() text.data = str(self.UID) subtag.appendChild(text) xml.appendChild(subtag) if self.timeStart is not None: subtag = Element("ChapterTimeStart") text = Text() m, ms = divmod(self.timeStart, 60 * 10**9) s1 = ms / 10**9 h1, m1 = divmod(m, 60) text.data = f"{h1}:{m1:02d}:{s1:012.9f}" subtag.appendChild(text) xml.appendChild(subtag) if self.timeEnd is not None: subtag = Element("ChapterTimeEnd") text = Text() m, ms = divmod(self.timeEnd, 60 * 10**9) s1 = ms / 10**9 h1, m1 = divmod(m, 60) text.data = f"{h1}:{m1:02d}:{s1:012.9f}" subtag.appendChild(text) xml.appendChild(subtag) subtag = Element("ChapterFlagHidden") text = Text() text.data = str(int(bool(self.hidden))) subtag.appendChild(text) xml.appendChild(subtag) subtag = Element("ChapterFlagEnabled") text = Text() text.data = str(int(bool(self.enabled))) subtag.appendChild(text) xml.appendChild(subtag) # TODO if self.segmentUID is not None: pass if self.segmentEditionUID is not None: pass if self.tracks is not None: pass for display in self.displays: xml.appendChild(display.toXml()) return xml
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 toXml(self): xml = Element("EditionEntry") subtag = Element("EditionUID") text = Text() text.data = str(self.UID) subtag.appendChild(text) xml.appendChild(subtag) subtag = Element("EditionFlagHidden") text = Text() text.data = str(int(bool(self.hidden))) subtag.appendChild(text) xml.appendChild(subtag) subtag = Element("EditionFlagDefault") text = Text() text.data = str(int(bool(self.default))) subtag.appendChild(text) xml.appendChild(subtag) subtag = Element("EditionFlagOrdered") text = Text() text.data = str(int(bool(self.ordered))) subtag.appendChild(text) xml.appendChild(subtag) for chapter in self: xml.appendChild(chapter.toXml()) return xml
def toXml(self): xml = Element("ChapterDisplay") subtag = Element("ChapterString") text = Text() text.data = self.string subtag.appendChild(text) xml.appendChild(subtag) for lang in self.languages: subtag = Element("ChapterLanguage") text = Text() text.data = lang subtag.appendChild(text) xml.appendChild(subtag) for lang in self.langIETF: subtag = Element("ChapterLanguageIETF") text = Text() text.data = lang subtag.appendChild(text) xml.appendChild(subtag) for country in self.countries: subtag = Element("ChapterCountry") text = Text() text.data = country subtag.appendChild(text) xml.appendChild(subtag) return xml
def _MakeTextElem(self, textcontent): """ Text Element construction helper since python2.2 and python 2.3 use different implementations of the text element """ # 2.3 Text class first try: textElem = Text() textElem.data = textcontent except TypeError: textElem = Text(textcontent) return textElem
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 write_flames(logger, title='flames'): base_path = os.path.join( FLAMES_DIR, datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), ) out_txt_path = base_path + '.txt' out_svg_path = base_path + '.svg' title_element = Text() title_element.data = title title_xml = title_element.toxml() with open(out_txt_path, 'w') as out_txt: write_samples(out_txt, logger.samples) with open(out_svg_path, 'w') as out_svg: subprocess.call([ 'perl', FLAMEGRAPH_SCRIPT_PATH, out_txt_path, '--title', title_xml, ], stdout=out_svg)
def set(self, value): while self.hasChildNodes(): del self.childNodes[0] if value is not None: textnode = Text() textnode.data = value self.appendChild(textnode)
def __init__(self, fields, idcol, action, record, **atts): BaseElement.__init__(self, 'table', **atts) self.record = record refdata = None if hasattr(record, '_refdata'): refdata = record._refdata for field in fields: row = BaseElement('tr') key = TD(bgcolor='DarkSeaGreen') key.appendChild(Bold(field)) row.appendChild(key) val = TD() if refdata is not None and field in refdata.cols: ridcol = refdata.cols[field] refrec = refdata.data[field][record[ridcol]] node = refdata.object[field](refrec) if action: url = '.'.join(map(str, [action, field, record[idcol]])) val.appendChild(Anchor(url, node)) else: val.appendChild(node) elif action: url = '.'.join(map(str, [action, field, record[idcol]])) val.appendChild(Anchor(url, record[field])) else: node = Text() node.data = record[field] val.appendChild(node) row.appendChild(val) self.val = val self.key = key self.appendChild(row)
def dict2xml(d, root_node=None): wrap = False if None == root_node or isinstance(d, list) else True root = 'objects' if None == root_node else root_node root_singular = root[:-1] if 's' == root[-1] and None == root_node else root xml = '' children = [] if isinstance(d, dict): for key, value in dict.items(d): if isinstance(value, dict): children.append(dict2xml(value, key)) elif isinstance(value, list): children.append(dict2xml(value, key)) else: t = Text() t.data = unicode(value) xml = xml + ' ' + key + '="' + t.toxml() + '"' else: for value in d: children.append(dict2xml(value, root_singular)) end_tag = '>' if 0 < len(children) else '/>' if wrap or isinstance(d, dict): xml = '<' + root + xml + end_tag if 0 < len(children): for child in children: xml = xml + child if wrap or isinstance(d, dict): xml = xml + '</' + root + '>' return xml
def insert_output_values(self, text): """ Replace all the ${variables} in text with xpaths. Returns that and a boolean indicating if there were any ${variables} present. """ # There was a bug where escaping is completely turned off in labels # where variable replacement is used. # For exampke, `${name} < 3` causes an error but `< 3` does not. # This is my hacky fix for it, which does string escaping prior to # variable replacement: from xml.dom.minidom import Text text_node = Text() text_node.data = text xml_text = text_node.toxml() bracketed_tag = r"\$\{(.*?)\}" # need to make sure we have reason to replace # since at this point < is <, # the net effect < gets translated again to &lt; if unicode(xml_text).find('{') != -1: result = re.sub( bracketed_tag, self._var_repl_output_function, unicode(xml_text)) return result, not result == xml_text return text, False
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 toXml(self): xml = Element("Simple") child = Element("Name") text = Text() text.data = self.name child.appendChild(text) xml.appendChild(child) if self.string is not None: child = Element("String") text = Text() text.data = self.string child.appendChild(text) xml.appendChild(child) if self.binary is not None: child = Element("Binary") text = Text() text.data = base64.encodebytes(self.binary).decode("utf8") child.appendChild(text) xml.appendChild(child) if self.language is not None: child = Element("TagLanguage") text = Text() text.data = self.language child.appendChild(text) xml.appendChild(child) if self.default: child = Element("DefaultLanguage") text = Text() text.data = "1" child.appendChild(text) xml.appendChild(child) for subtag in self.subtags: xml.appendChild(subtag.toXml()) return xml
def test_splitIntoSlides(self): """ L{splitIntoSlides} accepts a document and returns a list of two-tuples, each element of which contains the title of a slide taken from an I{h2} element and the body of that slide. """ parent = Element('html') body = Element('body') parent.appendChild(body) first = Element('h2') text = Text() text.data = 'first slide' first.appendChild(text) body.appendChild(first) body.appendChild(Element('div')) body.appendChild(Element('span')) second = Element('h2') text = Text() text.data = 'second slide' second.appendChild(text) body.appendChild(second) body.appendChild(Element('p')) body.appendChild(Element('br')) slides = splitIntoSlides(parent) self.assertEqual(slides[0][0], 'first slide') firstContent = slides[0][1] self.assertEqual(firstContent[0].tagName, 'div') self.assertEqual(firstContent[1].tagName, 'span') self.assertEqual(len(firstContent), 2) self.assertEqual(slides[1][0], 'second slide') secondContent = slides[1][1] self.assertEqual(secondContent[0].tagName, 'p') self.assertEqual(secondContent[1].tagName, 'br') self.assertEqual(len(secondContent), 2) self.assertEqual(len(slides), 2)
def html_content(self, info_html): """Return <HtmlContent> tag with escaped HTML. :param str info_html: Info HTML """ doc = Document() el = doc.createElement('HtmlContent') el.setAttribute('inline', '1') text = Text() text.data = info_html el.appendChild(text) return el.toxml()
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_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_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_titleWithHeader(self): """ L{TexiSpitter.visitNode} emits I{@subsection} and I{@menu} blocks when it encounters a header (h2 or h3) in a I{title} element. """ titleElement = Element('title') text = Text() text.data = u'bar' titleElement.appendChild(text) head = Element('h2') first = Text() first.data = u'header1' head.appendChild(first) titleElement.appendChild(head) self.spitter.visitNode(titleElement) self.assertEqual( ''.join(self.output), '@node bar\n\n@node header1\n\n\n@subsection header1\n\n' '@section bar\n\n@node header1\n\n\n@subsection header1\n\n' '@menu\n* header1::\n@end menu\n')
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 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 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 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 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 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 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>')
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)