示例#1
0
    def test_generateTableOfContents(self):
        """
        L{tree.generateToC} returns an element which contains a table of
        contents generated from the headers in the document passed to it.
        """
        parent = dom.Element('body')
        header = dom.Element('h2')
        text = dom.Text()
        text.data = u'header & special character'
        header.appendChild(text)
        parent.appendChild(header)
        subheader = dom.Element('h3')
        text = dom.Text()
        text.data = 'subheader'
        subheader.appendChild(text)
        parent.appendChild(subheader)

        tableOfContents = tree.generateToC(parent)
        self.assertEqual(
            tableOfContents.toxml(),
            '<ol><li><a href="#auto0">header &amp; special character</a></li><ul><li><a href="#auto1">subheader</a></li></ul></ol>'
        )

        self.assertEqual(
            header.toxml(),
            '<h2>header &amp; special character<a name="auto0"/></h2>')

        self.assertEqual(subheader.toxml(),
                         '<h3>subheader<a name="auto1"/></h3>')
示例#2
0
def setAuthors(template, authors):
    """
    Add author information to the template document.

    Names and contact information for authors are added to each node with a
    C{class} attribute set to C{authors} and to the template head as C{link}
    nodes.

    @type template: A DOM Node or Document
    @param template: The output template which defines the presentation of the
    version information.

    @type authors: C{list} of two-tuples of C{str}
    @param authors: List of names and contact information for the authors of
    the input document.

    @return: C{None}
    """

    for node in domhelpers.findElementsWithAttribute(template, "class",
                                                     'authors'):

        # First, similarly to setTitle, insert text into an <div
        # class="authors">
        container = dom.Element('span')
        for name, href in authors:
            anchor = dom.Element('a')
            anchor.setAttribute('href', href)
            anchorText = dom.Text()
            anchorText.data = name
            anchor.appendChild(anchorText)
            if (name, href) == authors[-1]:
                if len(authors) == 1:
                    container.appendChild(anchor)
                else:
                    andText = dom.Text()
                    andText.data = 'and '
                    container.appendChild(andText)
                    container.appendChild(anchor)
            else:
                container.appendChild(anchor)
                commaText = dom.Text()
                commaText.data = ', '
                container.appendChild(commaText)

        node.appendChild(container)

    # Second, add appropriate <link rel="author" ...> tags to the <head>.
    head = domhelpers.findNodesNamed(template, 'head')[0]
    authors = [
        dom.parseString('<link rel="author" href="%s" title="%s"/>' %
                        (href, name)).childNodes[0] for name, href in authors
    ]
    head.childNodes.extend(authors)
示例#3
0
文件: feed.py 项目: ripudamank2/pkg5
def set_title(depot, doc, feed, update_ts):
        """This function attaches the necessary RSS/Atom feed elements needed
        to provide title, author and contact information to the provided
        xmini document object using the provided feed object and update
        time.
        """

        t = doc.createElement("title")
        ti = xmini.Text()
        ti.replaceWholeText(depot.cfg.get_property("pkg_bui", "feed_name"))
        t.appendChild(ti)
        feed.appendChild(t)

        l = doc.createElement("link")
        l.setAttribute("href", cherrypy.url())
        l.setAttribute("rel", "self")
        feed.appendChild(l)

        # Atom requires each feed to have a permanent, universally unique
        # identifier.
        i = doc.createElement("id")
        it = xmini.Text()
        netloc, path = urlparse(cherrypy.url())[1:3]
        netloc = netloc.split(":", 1)[0]
        tag = "tag:{0},{1}:{2}".format(netloc, update_ts.strftime("%Y-%m-%d"),
            path)
        it.replaceWholeText(tag)
        i.appendChild(it)
        feed.appendChild(i)

        # Indicate when the feed was last updated.
        u = doc.createElement("updated")
        ut = xmini.Text()
        ut.replaceWholeText(dt_to_rfc3339_str(update_ts))
        u.appendChild(ut)
        feed.appendChild(u)

        # Add our icon.
        i = doc.createElement("icon")
        it = xmini.Text()
        it.replaceWholeText(depot.cfg.get_property("pkg_bui", "feed_icon"))
        i.appendChild(it)
        feed.appendChild(i)

        # Add our logo.
        l = doc.createElement("logo")
        lt = xmini.Text()
        lt.replaceWholeText(depot.cfg.get_property("pkg_bui", "feed_logo"))
        l.appendChild(lt)
        feed.appendChild(l)
示例#4
0
def create_vec_lst_tag(tag_name, lst):
    """Creates an XML tag containing the specified vector list."""
    tag = dom.Element(tag_name)
    text = dom.Text()
    text.data = vec_lst_to_str(lst)
    tag.appendChild(text)
    return tag
示例#5
0
def numberDocument(document, chapterNumber):
    """
    Number the sections of the given document.

    A dot-separated chapter, section number is added to the beginning of each
    section, as defined by C{h2} nodes.

    This is probably intended to interact in a rather specific way with
    L{getSectionNumber}.

    @type document: A DOM Node or Document
    @param document: The input document which contains all of the content to be
    presented.

    @type chapterNumber: C{int}
    @param chapterNumber: The chapter number of this content in an overall
    document.

    @return: C{None}
    """
    i = 1
    for node in domhelpers.findNodesNamed(document, "h2"):
        label = dom.Text()
        label.data = "%s.%d " % (chapterNumber, i)
        node.insertBefore(label, node.firstChild)
        i += 1
	def _save_project( self, filename ):
		"Output the project XML to a file"
		self._project.filename = filename
		self._saving_project = True
		
		# TODO: Compile an XML document out of self._project and save it
		out_xml = minidom.Document()
		out_xml.version = 1.0

		gedit_project_element = minidom.Element( 'gedit-project' )

		for subfilename in self._project.get_files():
			file_element = minidom.Element( 'file' )
			text_node = minidom.Text()
			text_node.data = subfilename
			file_element.childNodes.append( text_node )
			gedit_project_element.childNodes.append( file_element )

		out_xml.childNodes.append( gedit_project_element )

		outfile = file( self._project.filename, "w" )
		outfile.writelines( out_xml.toprettyxml() )
		outfile.close()

		self._saving_project = False
		print "Saving project ... " + self._project.filename
示例#7
0
def munge(document, template, linkrel, d, fullpath, ext, url, config):
    # FIXME: This has *way* to much duplicated crap in common with tree.munge
    #fixRelativeLinks(template, linkrel)
    removeH1(document)
    fixAPI(document, url)
    fontifyPython(document)
    addPyListings(document, d)
    addHTMLListings(document, d)
    #fixLinks(document, ext)
    #putInToC(template, generateToC(document))
    template = template.cloneNode(1)

    # Insert the slides into the template
    slides = []
    pos = 0
    for title, slide in splitIntoSlides(document):
        t = template.cloneNode(1)
        text = dom.Text()
        text.data = title
        setTitle(t, [text])
        tmplbody = domhelpers.findElementsWithAttribute(t, "class", "body")[0]
        tmplbody.childNodes = slide
        tmplbody.setAttribute("class", "content")
        # FIXME: Next/Prev links
        # FIXME: Perhaps there should be a "Template" class?  (setTitle/setBody
        #        could be methods...)
        slides.append(HTMLSlide(t, title, pos))
        pos += 1

    insertPrevNextLinks(slides, os.path.splitext(os.path.basename(fullpath)),
                        ext)

    return slides
示例#8
0
    def test_footnotes(self):
        """
        L{tree.footnotes} finds all of the nodes with the I{footnote} class in
        the DOM passed to it and adds a footnotes section to the end of the
        I{body} element which includes them.  It also inserts links to those
        footnotes from the original definition location.
        """
        parent = dom.Element('div')
        body = dom.Element('body')
        footnote = dom.Element('span')
        footnote.setAttribute('class', 'footnote')
        text = dom.Text()
        text.data = 'this is the footnote'
        footnote.appendChild(text)
        body.appendChild(footnote)
        body.appendChild(dom.Element('p'))
        parent.appendChild(body)

        tree.footnotes(parent)

        self.assertEqual(
            parent.toxml(), '<div><body>'
            '<a href="#footnote-1" title="this is the footnote">'
            '<super>1</super>'
            '</a>'
            '<p/>'
            '<h2>Footnotes</h2>'
            '<ol><li><a name="footnote-1">'
            '<span class="footnote">this is the footnote</span>'
            '</a></li></ol>'
            '</body></div>')
示例#9
0
 def close_menu(self):
     self.value = self.menu[2]
     try:
         self.node.childNodes[0].nodeValue = self.value.decode('utf-8')
     except IndexError:
         t = minidom.Text()
         self.node.childNodes.append(t)
         t.nodeValue = self.value.decode('utf-8')
示例#10
0
    def setTextContent(self, data):
        for node in self._node.childNodes:
            if node.nodeType == DOM.Node.TEXT_NODE:
                self._node.removeChild(node)

        text = DOM.Text()
        text.data = data.decode("utf8")

        self._node.appendChild(text)
示例#11
0
    def build_text(self, data):
        """Builds XML text element

        :param data:
        :return: :class:`~xml.dom.minidom.Text`
        """
        t = minidom.Text()
        t.data = data
        return t
示例#12
0
def filterPoints(kmlFile, filterStep=2):

    xmldoc = minidom.parse(kmlFile)
    mainDoc = xmldoc.getElementsByTagName('Document')[0]
    coords_all = list()
    for elem in xmldoc.getElementsByTagName('Placemark'):
        for lineString in elem.getElementsByTagName('LineString'):
            coordsNode = lineString.getElementsByTagName(
                'coordinates')[0].childNodes[0]
            coords_old = coordsNode.data.strip().split('\n')
            if len(coords_old) >= filterStep:
                coords_new = coords_old[0:-1:filterStep]
                coords_new.append(coords_old[-1])
                coords_all.extend(coords_new)
            else:
                coords_all.extend(coords_old)

    node_placemark = xmldoc.createElement('Placemark')
    node_name = xmldoc.createElement('name')
    text_name = minidom.Text()
    text_name.data = 'Cycling compilation'
    node_lineString = xmldoc.createElement('LineString')

    node_tesselate = xmldoc.createElement('tesselate')

    node_coords = xmldoc.createElement('coordinates')
    text_coords = minidom.Text()

    mainDoc.appendChild(node_placemark)
    node_placemark.appendChild(node_name)
    node_placemark.appendChild(node_lineString)
    node_lineString.appendChild(node_tesselate)
    node_lineString.appendChild(node_coords)
    node_coords.appendChild(text_coords)
    node_name.appendChild(text_name)

    # coords_final = coords_all[0:-1:filterStep]
    # coords_final.append(coords_all[-1])
    # text_coords.data = '\n'.join(coords_final)
    text_coords.data = '\n'.join(coords_all)

    filename, ext = os.path.splitext(kmlFile)
    newfilename = '%s_SIMPLIFIED%s' % (filename, ext)
    _writeXmlDoc(xmldoc, newfilename)
示例#13
0
文件: io.py 项目: vishalbelsare/PRIMO
    def create_node_tag(self, node):
        '''
        Create a node tag that will look like:
        <VARIABLE TYPE="nature">
            <NAME>node_name</NAME>
            <OUTCOME>...</OUTCOME>
            <OUTCOME>...</OUTCOME>
            <PROPERTY>position = (x, y)</PROPERTY>
        </VARIABLE>

        Keyword arguments:
        node -- a Node with valid name and position

        Returns a XMLBIF conform "variable" tag
        '''
        if not isinstance(node, primo.nodes.Node):
            raise Exception("Node " + str(node) + " is not a Node.")
        tag_var = minidom.Element("VARIABLE")
        tag_own = minidom.Element("NAME")
        tag_pos = minidom.Element("PROPERTY")
        tag_var.setAttribute("TYPE", "nature")

        # set node name
        txt_name = minidom.Text()
        txt_name.data = node.name
        tag_var.appendChild(tag_own)
        tag_own.appendChild(txt_name)

        # set outcomes
        for value in node.value_range:
            tag_outcome = minidom.Element("OUTCOME")
            txt_outcome = minidom.Text()
            txt_outcome.data = value
            tag_outcome.appendChild(txt_outcome)
            tag_var.appendChild(tag_outcome)

        # set position
        txt_pos = minidom.Text()
        x, y = node.position
        txt_pos.data = "position = (" + str(x) + ", " + str(y) + ")"
        tag_pos.appendChild(txt_pos)
        tag_var.appendChild(tag_pos)

        return tag_var
示例#14
0
def _append_child_tag(node, tag, value, attr=None, attr_val=None):
    text = minidom.Text()
    text.data = value
    child = minidom.Element(tag)
    child.appendChild(text)

    if attr:
        child.setAttribute(attr, attr_val)

    node.appendChild(child)
示例#15
0
def set_node_text_value(node, text):
    if len(node.childNodes) == 0:
        text_node = minidom.Text()
        node.appendChild(text_node)
    elif len(node.childNodes) == 1:
        text_node = node.firstChild
    else:
        raise Error('Invalid node with text value: %r' % node.toxml())
    assert (text_node.nodeType == Element.TEXT_NODE), node.toxml()
    text_node.data = text
示例#16
0
def erstelle_eintrag(schluessel, wert):
    tag_eintrag = dom.Element("eintrag")
    tag_schluessel = dom.Element("schluessel")
    tag_wert = dom.Element("wert")

    tag_schluessel.setAttribute("typ", type(schluessel).__name__)
    tag_wert.setAttribute("typ", type(wert).__name__)

    text = dom.Text()
    text.data = str(schluessel)
    tag_schluessel.appendChild(text)

    text = dom.Text()
    text.data = str(wert)
    tag_wert.appendChild(text)

    tag_eintrag.appendChild(tag_schluessel)
    tag_eintrag.appendChild(tag_wert)
    return tag_eintrag
示例#17
0
 def test_getSectionNumber(self):
     """
     L{tree.getSectionNumber} accepts an I{H2} element and returns its text
     content.
     """
     header = dom.Element('foo')
     text = dom.Text()
     text.data = 'foobar'
     header.appendChild(text)
     self.assertEqual(tree.getSectionNumber(header), 'foobar')
示例#18
0
 def character_data_handler(self, data):
     childNodes = self.curNode.childNodes
     if childNodes and childNodes[-1].nodeType == TEXT_NODE:
         node = childNodes[-1]
         node.data = node.data + data
         return
     node = minidom.Text()
     node.data = node.data + data
     node.ownerDocument = self.document
     _append_child(self.curNode, node)
示例#19
0
 def set_value(self, value):
     """set_value(value) - sets new value (data) of element. value must be unicode string if it contains any non ascii characters"""
     # at first: delete all text child nodes
     for node in self.element.childNodes:
         if node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
             self.element.removeChild(node)
     textNode = minidom.Text()
     textNode._set_data(value)
     self.element.insertBefore(textNode, self.element.firstChild)
     self._updatedata()
     return self.value
示例#20
0
    def addElementText(self, name, val):
        t = minidom.Text()
        if val:
            t.data = unicode(val)
        else:
            t.data = ""
        t.ownerDocument = self.ownerDocument

        e = self.addElement(name)
        e.appendChild(t)
        return e
示例#21
0
 def __init__(self, tag, attrib=None, text='', children=()):
     mdom.Element.__init__(self, tag)
     if attrib is not None:
         for k, v in attrib.items():
             if None not in (k, v):
                 self.setAttribute(k, v)
     if text:
         self.appendChild(mdom.Text())
         self.firstChild.replaceWholeText(text)
     for child in children:
         self.appendChild(child)
示例#22
0
 def character_data_handler(self, data):
     childNodes = self.curNode.childNodes
     if childNodes and childNodes[-1].nodeType == TEXT_NODE:
         node = childNodes[-1]
         d = node.__dict__
         d['data'] = d['nodeValue'] = node.data + data
         return
     node = minidom.Text()
     d = node.__dict__
     d['data'] = d['nodeValue'] = node.data + data
     d['ownerDocument'] = self.document
     _append_child(self.curNode, node)
示例#23
0
    def setTextContent(self, data):
        for node in self._node.childNodes:
            if node.nodeType == DOM.Node.TEXT_NODE:
                self._node.removeChild(node)

        text = DOM.Text()
        try:
            text.data = data.decode("utf8", errors='ignore')
        except UnicodeEncodeError:
            pass

        self._node.appendChild(text)
示例#24
0
 def addItem(headerElement, parent):
     anchor = dom.Element('a')
     name = 'auto%d' % (auto(), )
     anchor.setAttribute('href', '#' + name)
     text = dom.Text()
     text.data = domhelpers.getNodeText(headerElement)
     anchor.appendChild(text)
     headerNameItem = dom.Element('li')
     headerNameItem.appendChild(anchor)
     parent.appendChild(headerNameItem)
     anchor = dom.Element('a')
     anchor.setAttribute('name', name)
     headerElement.appendChild(anchor)
示例#25
0
    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
示例#26
0
    def test_numberDocument(self):
        """
        L{tree.numberDocument} inserts section numbers into the text of each
        header.
        """
        parent = dom.Element('foo')
        section = dom.Element('h2')
        text = dom.Text()
        text.data = 'foo'
        section.appendChild(text)
        parent.appendChild(section)

        tree.numberDocument(parent, '7')

        self.assertEqual(section.toxml(), '<h2>7.1 foo</h2>')
示例#27
0
 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'))
示例#28
0
def addMtime(document, fullpath):
    """
    Set the last modified time of the given document.

    @type document: A DOM Node or Document
    @param document: The output template which defines the presentation of the
    last modified time.

    @type fullpath: C{str}
    @param fullpath: The file name from which to take the last modified time.

    @return: C{None}
    """
    for node in domhelpers.findElementsWithAttribute(document, "class",
                                                     "mtime"):
        txt = dom.Text()
        txt.data = time.ctime(os.path.getmtime(fullpath))
        node.appendChild(txt)
示例#29
0
def setVersion(template, version):
    """
    Add a version indicator to the given template.

    @type template: A DOM Node or Document
    @param template: The output template which defines the presentation of the
    version information.

    @type version: C{str}
    @param version: The version string to add to the template.

    @return: C{None}
    """
    for node in domhelpers.findElementsWithAttribute(template, "class",
                                                     "version"):
        text = dom.Text()
        text.data = version
        node.appendChild(text)
示例#30
0
 def character_data_handler_cdata(self, data):
     childNodes = self.curNode.childNodes
     if self._cdata:
         if (self._cdata_continue
                 and childNodes[-1].nodeType == CDATA_SECTION_NODE):
             childNodes[-1].appendData(data)
             return
         node = self.document.createCDATASection(data)
         self._cdata_continue = True
     elif childNodes and childNodes[-1].nodeType == TEXT_NODE:
         node = childNodes[-1]
         value = node.data + data
         node.data = value
         return
     else:
         node = minidom.Text()
         node.data = data
         node.ownerDocument = self.document
     _append_child(self.curNode, node)