Python xml.dom.minidom.Element() Examples

The following are 30 code examples of xml.dom.minidom.Element(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.dom.minidom , or try the search function .
Example #1
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_fixAPIBase(self):
        """
        If a node with the I{API} class and a value for the I{base} attribute
        is included in the DOM passed to L{tree.fixAPI}, the link added to that
        node refers to the API formed by joining the value of the I{base}
        attribute to the text contents of the node.
        """
        parent = dom.Element('div')
        link = dom.Element('span')
        link.setAttribute('class', 'API')
        link.setAttribute('base', 'bar')
        text = dom.Text()
        text.data = 'baz'
        link.appendChild(text)
        parent.appendChild(link)

        tree.fixAPI(parent, 'http://example.com/%s')

        self.assertEqual(
            parent.toxml(),
            '<div><span class="API">'
            '<a href="http://example.com/bar.baz" title="bar.baz">baz</a>'
            '</span></div>') 
Example #2
Source File: __init__.py    From xmind with MIT License 6 votes vote down vote up
def _elementConstructor(self, tag_name, namespaceURI=None, prefix=None, localName=None):
        return DOM.Element(tag_name,
                           namespaceURI,
                           self.getPrefix(tag_name),
                           self.getLocalName(tag_name))

        # _localName = self.getLocalName(tag_name)
        # element = DOM.Element(tag_name, namespaceURI, prefix, _localName)
        #
        # prefix = self.getPrefix(tag_name)
        # element.prefix = prefix
        #
        # return element

        # element = DOM.Element(tag_name, namespaceURI, prefix, localName)
        # prefix = self.getPrefix(tag_name)
        # localName = self.getLocalName(tag_name)
        # element.prefix = prefix
        # element.localName = localName
        # return element 
Example #3
Source File: kml.py    From sarpy with MIT License 6 votes vote down vote up
def add_line_style(self, pid=None, par=None, **params):
        """
        Add line style.

        Parameters
        ----------
        pid : None|str
            The id, which should not be set if this is a child of a style element.
        par : None|minidom.Element
            The parent node.
        params : dict
            The parameters dictionary.

        Returns
        -------
        None
        """

        sty = self._create_new_node(par, 'LineStyle')
        if pid is not None:
            sty.setAttribute('id', pid)
        self._add_conditional_text_node(sty, 'color', params, default='b0ff0000')
        self._add_conditional_text_node(sty, 'width', params, default='1.0') 
Example #4
Source File: kml.py    From sarpy with MIT License 6 votes vote down vote up
def add_label_style(self, pid=None, par=None, **params):
        """
        Add label style

        Parameters
        ----------
        pid : None|str
            The id, which should not be set if this is a child of a style element.
        par : None|minidom.Element
            The parent node.
        params : dict
            The parameters dictionary.

        Returns
        -------
        None
        """

        sty = self._create_new_node(par, 'LabelStyle')
        if pid is not None:
            sty.setAttribute('id', pid)
        self._add_conditional_text_node(sty, 'color', params, default='b0ff0000')
        self._add_conditional_text_node(sty, 'scale', params, default='1.0') 
Example #5
Source File: parse_svg.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
def plt_patch(node: minidom.Element, trans_parent_trans: mtransforms.Transform, style: dict, constructor: callable, ids: dict, no_draw: bool = False) -> mpatches.Patch:
    """ add a node to the figure by calling the provided constructor """
    trans_node = parseTransformation(node.getAttribute("transform"))
    style = get_inline_style(node, get_css_style(node, ids["css"], style))

    patch = constructor(node, trans_node + trans_parent_trans + plt.gca().transData, style, ids)
    if not isinstance(patch, list):
        patch = [patch]

    for p in patch:
        if not getattr(p, "is_marker", False):
            style = apply_style(style, p)
            p.style = style
            #p.set_transform(p.get_transform() + plt.gca().transData)
        p.trans_parent = trans_parent_trans
        p.trans_node = parseTransformation(node.getAttribute("transform"))

        if not no_draw and not styleNoDisplay(style):
                plt.gca().add_patch(p)
    if node.getAttribute("id") != "":
        ids[node.getAttribute("id")] = patch
    return patch 
Example #6
Source File: parse_svg.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
def get_css_style(node: minidom.Element, css_list: list, base_style: dict) -> dict:
    """ update the base_style with the style definitions from the stylesheet that are applicable to the node
        defined by the classes or id of the node
    """
    style = {}
    if base_style is not None:
        style.update(base_style)
    classes = node.getAttribute("class").split()
    for css in css_list:
        css_condition, css_style = css
        if css_condition[0] == "." and css_condition[1:] in classes:
            style.update(css_style)
        elif css_condition[0] == "#" and css_condition[1:] == node.getAttribute("id"):
            style.update(css_style)
        elif css_condition == node.tagName:
            style.update(css_style)
    return style 
Example #7
Source File: parse_svg.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
def get_inline_style(node: minidom.Element, base_style: dict = None) -> dict:
    """ update the basestyle with the style defined by the style property of the node """
    style = {}
    if base_style is not None:
        style.update(base_style)
    attribute_names = ["alignment-baseline", "baseline-shift", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-rendering", "cursor", "direction", "display", "dominant-baseline", "fill", "fill-opacity", "fill-rule", "filter", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "glyph-orientation-horizontal", "glyph-orientation-vertical", "image-rendering", "letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "overflow", "paint-order", "pointer-events", "shape-rendering", "stop-color", "stop-opacity", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", "text-overflow", "text-rendering", "unicode-bidi", "vector-effect", "visibility", "white-space", "word-spacing", "writing-mode"]
    for name in attribute_names:
        value = node.getAttribute(name)
        if value != "":
            style[name] = value

    for element in node.getAttribute("style").split(";"):
        if element == "":
            continue
        key, value = element.split(":", 1)
        style[key] = value
    return style 
Example #8
Source File: kml.py    From sarpy with MIT License 6 votes vote down vote up
def add_multi_geometry(self, par=None, **params):
        """
        Adds a MultiGeometry object. The MultiGeometry object is really just a container.
        The user must continue adding the primitive Geometry constituents to this container or
        nothing will actually get rendered.

        Parameters
        ----------
        par : None|minidom.Element
            The parent node. If not given, then a Placemark is created.
        params : dict
            The parameters dictionary

        Returns
        -------
        minidom.Element
        """

        if par is None:
            par = self.add_container(**params)
        multigeometry_node = self._create_new_node(par, 'MultiGeometry')
        return multigeometry_node 
Example #9
Source File: SVGExporter.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def cleanXml(node):
    ## remove extraneous text; let the xml library do the formatting.
    hasElement = False
    nonElement = []
    for ch in node.childNodes:
        if isinstance(ch, xml.Element):
            hasElement = True
            cleanXml(ch)
        else:
            nonElement.append(ch)
    
    if hasElement:
        for ch in nonElement:
            node.removeChild(ch)
    elif node.tagName == 'g':  ## remove childless groups
        node.parentNode.removeChild(node) 
Example #10
Source File: kml.py    From sarpy with MIT License 6 votes vote down vote up
def _add_lod(self, par, **params):
        """
        Adds a Level of Detail (LOD) element, which is explicitly a child of Region.

        Parameters
        ----------
        par : minidom.Element
        params : dict

        Returns
        -------
        minidom.Element
        """

        lod = self._create_new_node(par, 'Lod')
        self._add_conditional_text_node(lod, 'minLodPixels', params, '128')
        self._add_conditional_text_node(lod, 'maxLodPixels', params, '-1')
        self._add_conditional_text_node(lod, 'minFadeExtent', params, '0')
        return lod 
Example #11
Source File: kml.py    From sarpy with MIT License 6 votes vote down vote up
def add_poly_style(self, pid=None, par=None, **params):
        """
        Add poly style.

        Parameters
        ----------
        pid : None|str
            The id, which should not be set if this is a child of a style element.
        par : None|minidom.Element
            The parent node.
        params : dict
            The parameters dictionary.

        Returns
        -------
        None
        """

        sty = self._create_new_node(par, 'PolyStyle')
        if pid is not None:
            sty.setAttribute('id', pid)
        self._add_conditional_text_node(sty, 'color', params, default='80ff0000')
        self._add_conditional_text_node(sty, 'fill', params)
        self._add_conditional_text_node(sty, 'outline', params) 
Example #12
Source File: test_docbook.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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>') 
Example #13
Source File: test_slides.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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>') 
Example #14
Source File: distrib.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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()} 
Example #15
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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')) 
Example #16
Source File: tree.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _makeLineNumbers(howMany):
    """
    Return an element which will render line numbers for a source listing.

    @param howMany: The number of lines in the source listing.
    @type howMany: C{int}

    @return: An L{dom.Element} which can be added to the document before
        the source listing to add line numbers to it.
    """
    # Figure out how many digits wide the widest line number label will be.
    width = len(str(howMany))

    # Render all the line labels with appropriate padding
    labels = ['%*d' % (width, i) for i in range(1, howMany + 1)]

    # Create a p element with the right style containing the labels
    p = dom.Element('p')
    p.setAttribute('class', 'py-linenumber')
    t = dom.Text()
    t.data = '\n'.join(labels) + '\n'
    p.appendChild(t)
    return p 
Example #17
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_findNodeJustBefore(self):
        """
        L{tree.findNodeJustBefore} returns the previous sibling of the node it
        is passed.  The list of nodes passed in is ignored.
        """
        parent = dom.Element('div')
        result = dom.Element('foo')
        target = dom.Element('bar')
        parent.appendChild(result)
        parent.appendChild(target)

        self.assertIdentical(
            tree.findNodeJustBefore(target, [parent, result]),
            result)

        # Also, support other configurations.  This is a really not nice API.
        newTarget = dom.Element('baz')
        target.appendChild(newTarget)
        self.assertIdentical(
            tree.findNodeJustBefore(newTarget, [parent, result]),
            result) 
Example #18
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_notes(self):
        """
        L{tree.notes} inserts some additional markup before the first child of
        any node with the I{note} class.
        """
        parent = dom.Element('div')
        noteworthy = dom.Element('span')
        noteworthy.setAttribute('class', 'note')
        noteworthy.appendChild(dom.Element('foo'))
        parent.appendChild(noteworthy)

        tree.notes(parent)

        self.assertEqual(
            noteworthy.toxml(),
            '<span class="note"><strong>Note: </strong><foo/></span>') 
Example #19
Source File: tree.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def findNodeJustBefore(target, nodes):
    """
    Find the last Element which is a sibling of C{target} and is in C{nodes}.

    @param target: A node the previous sibling of which to return.
    @param nodes: A list of nodes which might be the right node.

    @return: The previous sibling of C{target}.
    """
    while target is not None:
        node = target.previousSibling
        while node is not None:
            if node in nodes:
                return node
            node = node.previousSibling
        target = target.parentNode
    raise RuntimeError("Oops") 
Example #20
Source File: test_latex.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_head(self):
        """
        L{LatexSpitter.visitNode} writes out author information for each
        I{link} element with a I{rel} attribute set to I{author}.
        """
        head = Element('head')
        first = Element('link')
        first.setAttribute('rel', 'author')
        first.setAttribute('title', 'alice')
        second = Element('link')
        second.setAttribute('rel', 'author')
        second.setAttribute('href', 'http://example.com/bob')
        third = Element('link')
        third.setAttribute('rel', 'author')
        third.setAttribute('href', 'mailto:carol@example.com')
        head.appendChild(first)
        head.appendChild(second)
        head.appendChild(third)

        self.spitter.visitNode(head)

        self.assertEqual(
            ''.join(self.output),
            '\\author{alice \\and $<$http://example.com/bob$>$ \\and $<$carol@example.com$>$}') 
Example #21
Source File: test_latex.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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}}") 
Example #22
Source File: test_latex.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_anchorListingSkipLines(self):
        """
        When passed an I{a} element with a I{listing} class and an I{skipLines}
        attribute, L{LatexSpitter.visitNode} emits a verbatim block which skips
        the indicated number of lines from the beginning of the source listing.
        """
        path = FilePath(self.mktemp())
        path.setContent('foo\nbar\n')
        listing = Element('a')
        listing.setAttribute('class', 'listing')
        listing.setAttribute('skipLines', '1')
        listing.setAttribute('href', path.path)
        self.spitter.visitNode(listing)
        self.assertEqual(
            ''.join(self.output),
            "\\begin{verbatim}\n"
            "bar\n"
            "\\end{verbatim}\\parbox[b]{\\linewidth}{\\begin{center} --- "
            "\\begin{em}temp\\end{em}\\end{center}}") 
Example #23
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_setTitle(self):
        """
        L{tree.setTitle} inserts the given title into the first I{title}
        element and the first element with the I{title} class in the given
        template.
        """
        parent = dom.Element('div')
        firstTitle = dom.Element('title')
        parent.appendChild(firstTitle)
        secondTitle = dom.Element('span')
        secondTitle.setAttribute('class', 'title')
        parent.appendChild(secondTitle)

        titleNodes = [dom.Text()]
        # minidom has issues with cloning documentless-nodes.  See Python issue
        # 4851.
        titleNodes[0].ownerDocument = dom.Document()
        titleNodes[0].data = 'foo bar'

        tree.setTitle(parent, titleNodes, None)
        self.assertEqual(firstTitle.toxml(), '<title>foo bar</title>')
        self.assertEqual(
            secondTitle.toxml(), '<span class="title">foo bar</span>') 
Example #24
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_setTitleWithChapter(self):
        """
        L{tree.setTitle} includes a chapter number if it is passed one.
        """
        document = dom.Document()

        parent = dom.Element('div')
        parent.ownerDocument = document

        title = dom.Element('title')
        parent.appendChild(title)

        titleNodes = [dom.Text()]
        titleNodes[0].ownerDocument = document
        titleNodes[0].data = 'foo bar'

        # Oh yea.  The numberer has to agree to put the chapter number in, too.
        numberer.setNumberSections(True)

        tree.setTitle(parent, titleNodes, '13')
        self.assertEqual(title.toxml(), '<title>13. foo bar</title>') 
Example #25
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_addMtime(self):
        """
        L{tree.addMtime} inserts a text node giving the last modification time
        of the specified file wherever it encounters an element with the
        I{mtime} class.
        """
        path = FilePath(self.mktemp())
        path.setContent('')
        when = time.ctime(path.getModificationTime())

        parent = dom.Element('div')
        mtime = dom.Element('span')
        mtime.setAttribute('class', 'mtime')
        parent.appendChild(mtime)

        tree.addMtime(parent, path.path)
        self.assertEqual(
            mtime.toxml(), '<span class="mtime">' + when + '</span>') 
Example #26
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_fontifyPythonNode(self):
        """
        L{tree.fontifyPythonNode} accepts a text node and replaces it in its
        parent with a syntax colored and line numbered version of the Python
        source it contains.
        """
        parent = dom.Element('div')
        source = dom.Text()
        source.data = 'def foo():\n    pass\n'
        parent.appendChild(source)

        tree.fontifyPythonNode(source)

        expected = """\
<div><pre class="python"><p class="py-linenumber">1
2
</p><span class="py-src-keyword">def</span> <span class="py-src-identifier">foo</span>():
    <span class="py-src-keyword">pass</span>
</pre></div>"""

        self.assertEqual(parent.toxml(), expected) 
Example #27
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_addPyListings(self):
        """
        L{tree.addPyListings} accepts a document with nodes with their I{class}
        attribute set to I{py-listing} and replaces those nodes with Python
        source listings from the file given by the node's I{href} attribute.
        """
        listingPath = FilePath(self.mktemp())
        listingPath.setContent('def foo():\n    pass\n')

        parent = dom.Element('div')
        listing = dom.Element('a')
        listing.setAttribute('href', listingPath.basename())
        listing.setAttribute('class', 'py-listing')
        parent.appendChild(listing)

        tree.addPyListings(parent, listingPath.dirname())

        expected = """\
<div><div class="py-listing"><pre><p class="py-linenumber">1
2
</p><span class="py-src-keyword">def</span> <span class="py-src-identifier">foo</span>():
    <span class="py-src-keyword">pass</span>
</pre><div class="caption"> - <a href="temp"><span class="filename">temp</span></a></div></div></div>"""

        self.assertEqual(parent.toxml(), expected) 
Example #28
Source File: test_lore.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_fixAPI(self):
        """
        The element passed to L{tree.fixAPI} has all of its children with the
        I{API} class rewritten to contain links to the API which is referred to
        by the text they contain.
        """
        parent = dom.Element('div')
        link = dom.Element('span')
        link.setAttribute('class', 'API')
        text = dom.Text()
        text.data = 'foo'
        link.appendChild(text)
        parent.appendChild(link)

        tree.fixAPI(parent, 'http://example.com/%s')
        self.assertEqual(
            parent.toxml(),
            '<div><span class="API">'
            '<a href="http://example.com/foo" title="foo">foo</a>'
            '</span></div>') 
Example #29
Source File: parser.py    From wechat-python-sdk with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _element2dict(self, parent):
        """
        将单个节点转换为 dict
        """
        d = {}
        for node in parent.childNodes:
            if not isinstance(node, minidom.Element):
                continue
            if not node.hasChildNodes():
                continue

            if node.childNodes[0].nodeType == minidom.Node.ELEMENT_NODE:
                try:
                    d[node.tagName]
                except KeyError:
                    d[node.tagName] = []
                d[node.tagName].append(self._element2dict(node))
            elif len(node.childNodes) == 1 and node.childNodes[0].nodeType in [minidom.Node.CDATA_SECTION_NODE, minidom.Node.TEXT_NODE]:
                d[node.tagName] = node.childNodes[0].data
        return d 
Example #30
Source File: kml.py    From sarpy with MIT License 5 votes vote down vote up
def add_linear_ring(self, coords, par=None, **params):
        """
        Adds a LinearRing element (closed linear path).

        Parameters
        ----------
        coords : str
            comma/space delimited string of coordinates for the outerRing. Format of the string
            :code:`'lon1,lat1,alt1 lon2,lat2,alt2 ...'` with the altitude values optional. If given, the altitude value
            is in meters. The precise interpretation of altitude (relative to the ground, relative to sea level, etc.)
            depends on the value of relevant tags passed down to the LinearRing objects, namely the values for the
            params entries:
                * 'extrude'
                * 'tessellate'
                * 'altitudeMode'
        par : None|minidom.Element
            The parent node. If not given, then a Placemark is created.
        params : dict
            The parameters dictionary.

        Returns
        -------
        minidom.Element
        """

        if par is None:
            par = self.add_container(params=params)
        linear_ring = self._create_new_node(par, 'LinearRing')

        for opt in ['extrude', 'tessellate', 'altitudeMode']:
            self._add_conditional_text_node(linear_ring, opt, params)
        self._add_text_node(linear_ring, 'coordinates', coords)
        return linear_ring