Python xml.etree.ElementTree.Comment() Examples

The following are 22 code examples of xml.etree.ElementTree.Comment(). 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.etree.ElementTree , or try the search function .
Example #1
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def writefile():
    """
    >>> elem = ET.Element("tag")
    >>> elem.text = "text"
    >>> serialize(elem)
    '<tag>text</tag>'
    >>> ET.SubElement(elem, "subtag").text = "subtext"
    >>> serialize(elem)
    '<tag>text<subtag>subtext</subtag></tag>'

    Test tag suppression
    >>> elem.tag = None
    >>> serialize(elem)
    'text<subtag>subtext</subtag>'
    >>> elem.insert(0, ET.Comment("comment"))
    >>> serialize(elem)     # assumes 1.3
    'text<!--comment--><subtag>subtext</subtag>'
    >>> elem[0] = ET.PI("key", "value")
    >>> serialize(elem)
    'text<?key value?><subtag>subtext</subtag>'
    """ 
Example #2
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def bug_200709_element_comment():
    """

    Not sure if this can be fixed, really (since the serializer needs
    ET.Comment, not cET.comment).

    >>> a = ET.Element('a')
    >>> a.append(ET.Comment('foo'))
    >>> a[0].tag == ET.Comment
    True

    >>> a = ET.Element('a')
    >>> a.append(ET.PI('foo'))
    >>> a[0].tag == ET.PI
    True

    """ 
Example #3
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def writefile():
    """
    >>> elem = ET.Element("tag")
    >>> elem.text = "text"
    >>> serialize(elem)
    '<tag>text</tag>'
    >>> ET.SubElement(elem, "subtag").text = "subtext"
    >>> serialize(elem)
    '<tag>text<subtag>subtext</subtag></tag>'

    Test tag suppression
    >>> elem.tag = None
    >>> serialize(elem)
    'text<subtag>subtext</subtag>'
    >>> elem.insert(0, ET.Comment("comment"))
    >>> serialize(elem)     # assumes 1.3
    'text<!--comment--><subtag>subtext</subtag>'
    >>> elem[0] = ET.PI("key", "value")
    >>> serialize(elem)
    'text<?key value?><subtag>subtext</subtag>'
    """ 
Example #4
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def bug_200709_element_comment():
    """

    Not sure if this can be fixed, really (since the serializer needs
    ET.Comment, not cET.comment).

    >>> a = ET.Element('a')
    >>> a.append(ET.Comment('foo'))
    >>> a[0].tag == ET.Comment
    True

    >>> a = ET.Element('a')
    >>> a.append(ET.PI('foo'))
    >>> a[0].tag == ET.PI
    True

    """ 
Example #5
Source File: spruce.py    From Spruce with GNU General Public License v3.0 6 votes vote down vote up
def add_output_metadata(root):
    """Build the main metadata and tags for an XML report.

    Args:
        root: Element to be used as the root for the report.
    """
    jss_connection = JSSConnection.get()
    report_date = ET.SubElement(root, "ReportDate")
    report_date.text = datetime.datetime.strftime(datetime.datetime.now(),
                                                  "%Y%m%d-%H%M%S")
    report_server = ET.SubElement(root, "Server")
    report_server.text = jss_connection.base_url
    api_user = ET.SubElement(root, "APIUser")
    api_user.text = jss_connection.user
    report_user = ET.SubElement(root, "LocalUser")
    report_user.text = os.getenv("USER")
    spruce_version = ET.SubElement(root, "SpruceVersion")
    spruce_version.text = __version__
    python_jss_version = ET.SubElement(root, "python-jssVersion")
    python_jss_version.text = jss.__version__
    removals = ET.SubElement(root, "Removals")
    removals.insert(0, ET.Comment("Move items to be removed here")) 
Example #6
Source File: parse.py    From eapeak with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def export_xml(self, filename=XML_FILE_NAME):
		"""
		Exports an XML file that can be reimported with the parseXMLFiles
		function.
		"""
		eapeakXML = ElementTree.Element('detection-run')
		eapeakXML.set('eapeak-version', __version__)
		eapeakXML.append(ElementTree.Comment(' Summary: Found ' + str(len(self.KnownNetworks)) + ' Network(s) '))
		eapeakXML.append(ElementTree.Comment(datetime.datetime.now().strftime(' Created %A %m/%d/%Y %H:%M:%S ')))
		networks = self.KnownNetworks.keys()
		if not networks:
			return
		networks.sort()
		for network in networks:
			eapeakXML.append(self.KnownNetworks[network].get_xml())
		xmldata = minidom.parseString(ElementTree.tostring(eapeakXML)).toprettyxml()
		if xmldata:
			tmpfile = open(filename, 'w')
			tmpfile.write(xmldata)
			tmpfile.close() 
Example #7
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bug_200709_element_comment():
    """

    Not sure if this can be fixed, really (since the serializer needs
    ET.Comment, not cET.comment).

    >>> a = ET.Element('a')
    >>> a.append(ET.Comment('foo'))
    >>> a[0].tag == ET.Comment
    True

    >>> a = ET.Element('a')
    >>> a.append(ET.PI('foo'))
    >>> a[0].tag == ET.PI
    True

    """ 
Example #8
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def writefile():
    """
    >>> elem = ET.Element("tag")
    >>> elem.text = "text"
    >>> serialize(elem)
    '<tag>text</tag>'
    >>> ET.SubElement(elem, "subtag").text = "subtext"
    >>> serialize(elem)
    '<tag>text<subtag>subtext</subtag></tag>'

    Test tag suppression
    >>> elem.tag = None
    >>> serialize(elem)
    'text<subtag>subtext</subtag>'
    >>> elem.insert(0, ET.Comment("comment"))
    >>> serialize(elem)     # assumes 1.3
    'text<!--comment--><subtag>subtext</subtag>'
    >>> elem[0] = ET.PI("key", "value")
    >>> serialize(elem)
    'text<?key value?><subtag>subtext</subtag>'
    """ 
Example #9
Source File: testlink.py    From xmind2testcase with MIT License 5 votes vote down vote up
def element_set_text(element, content):
    # retain html tags in content
    content = escape(content, entities={'\r\n': '<br />'})
    # replace new line for *nix system
    content = content.replace('\n', '<br />')
    # add the line break in source to make it readable
    content = content.replace('<br />', '<br />\n')

    # add CDATA for a element
    element.append(Comment(' --><![CDATA[' + content.replace(']]>', ']]]]><![CDATA[>') + ']]> <!-- ')) 
Example #10
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
def summarize(elem):
    if elem.tag == ET.Comment:
        return "<Comment>"
    return elem.tag 
Example #11
Source File: merge_xml.py    From se-blender with GNU General Public License v2.0 5 votes vote down vote up
def comment(self, data):
       self.start(ET.Comment, {})
       self.data(data)
       self.end(ET.Comment)

# WTF?! ElementTree overrides the Python declaration of XMLParser with some optimized-C version.
# Putting overriding methods on a class derived from that simply doesn't work.
# So we need to copy the whole fucking implementation of XMLParser where overriding ONE method would have sufficed! 
Example #12
Source File: Xml_Out.py    From ray_scripts with GNU General Public License v3.0 5 votes vote down vote up
def save_structure_map():
    pat_id = 'TPL_045_DAPD'
    m_logs_dir = os.path.join(log_dir, pat_id)
    filename = pat_id+'structure_map.xml'

    import xml.etree.ElementTree as ET
    # from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment
    from datetime import datetime, date
    from xml.dom import minidom


    top = ET.Element('StructureMap')

    d = datetime.now()
    comment = ET.Comment(d.isoformat())
    top.append(comment)

    protocol = ET.SubElement(top, 'protocol_structure')
    protocol.text = 'OTV4_4000'

    local_name = ET.SubElement(top, 'local_name')
    local_name.text = 'PTV1_MD'

    local_dose = ET.SubElement(top, 'local_dose')#, units='Gy')
    local_dose.text = '40'
    local_dose.set('units','Gy')

    print prettify(top)
    xmlstr = minidom.parseString(ET.tostring(top)).toprettyxml(indent="   ")
    full_path_filename = os.path.normpath('{}/{}'.format(m_logs_dir, filename))
    with open(full_path_filename, "w") as f:
        f.write(xmlstr)
    # ElementTree(top).write(os.path.normpath('{}/{}'.format(m_logs_dir, filename))) 
Example #13
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bug_200709_iter_comment():
    """

    >>> a = ET.Element('a')
    >>> b = ET.SubElement(a, 'b')
    >>> comment_b = ET.Comment("TEST-b")
    >>> b.append(comment_b)
    >>> summarize_list(a.iter(ET.Comment))
    ['<Comment>']

    """ 
Example #14
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def summarize(elem):
    if elem.tag == ET.Comment:
        return "<Comment>"
    return elem.tag 
Example #15
Source File: advancedsettings.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def comment(self, data):
        self.start(ET.Comment, {})
        self.data(data)
        self.end(ET.Comment) 
Example #16
Source File: xml_output.py    From flatten-tool with MIT License 5 votes vote down vote up
def toxml(
    data,
    xml_root_tag,
    xml_schemas=None,
    root_list_path="iati-activity",
    xml_comment=None,
):
    nsmap = {
        # This is "bound by definition" - see https://www.w3.org/XML/1998/namespace
        "xml": "http://www.w3.org/XML/1998/namespace"
    }
    root = dict_to_xml(data, xml_root_tag, nsmap=nsmap)
    if xml_schemas is not None:
        schema_dict = XMLSchemaWalker(xml_schemas).create_schema_dict(root_list_path)
        for element in root:
            sort_element(element, schema_dict)
    if xml_comment is None:
        xml_comment = "XML generated by flatten-tool"
    comment = ET.Comment(xml_comment)
    root.insert(0, comment)
    if USING_LXML:
        return ET.tostring(
            root, pretty_print=True, xml_declaration=True, encoding="utf-8"
        )
    else:
        return ET.tostring(root) 
Example #17
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
def bug_200709_iter_comment():
    """

    >>> a = ET.Element('a')
    >>> b = ET.SubElement(a, 'b')
    >>> comment_b = ET.Comment("TEST-b")
    >>> b.append(comment_b)
    >>> summarize_list(a.iter(ET.Comment))
    ['<Comment>']

    """ 
Example #18
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
def summarize(elem):
    if elem.tag == ET.Comment:
        return "<Comment>"
    return elem.tag 
Example #19
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
def bug_200709_iter_comment():
    """

    >>> a = ET.Element('a')
    >>> b = ET.SubElement(a, 'b')
    >>> comment_b = ET.Comment("TEST-b")
    >>> b.append(comment_b)
    >>> summarize_list(a.iter(ET.Comment))
    ['<Comment>']

    """

# --------------------------------------------------------------------
# reported on bugs.python.org 
Example #20
Source File: serializers.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def _serialize_html(write, elem, format):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % _escape_cdata(text))
    elif tag is ProcessingInstruction:
        write("<?%s?>" % _escape_cdata(text))
    elif tag is None:
        if text:
            write(_escape_cdata(text))
        for e in elem:
            _serialize_html(write, e, format)
    else:
        namespace_uri = None
        if isinstance(tag, QName):
            # QNAME objects store their data as a string: `{uri}tag`
            if tag.text[:1] == "{":
                namespace_uri, tag = tag.text[1:].split("}", 1)
            else:
                raise ValueError('QName objects must define a tag.')
        write("<" + tag)
        items = elem.items()
        if items:
            items = sorted(items)  # lexical order
            for k, v in items:
                if isinstance(k, QName):
                    # Assume a text only QName
                    k = k.text
                if isinstance(v, QName):
                    # Assume a text only QName
                    v = v.text
                else:
                    v = _escape_attrib_html(v)
                if k == v and format == 'html':
                    # handle boolean attributes
                    write(" %s" % v)
                else:
                    write(' {}="{}"'.format(k, v))
        if namespace_uri:
            write(' xmlns="%s"' % (_escape_attrib(namespace_uri)))
        if format == "xhtml" and tag.lower() in HTML_EMPTY:
            write(" />")
        else:
            write(">")
            if text:
                if tag.lower() in ["script", "style"]:
                    write(text)
                else:
                    write(_escape_cdata(text))
            for e in elem:
                _serialize_html(write, e, format)
            if tag.lower() not in HTML_EMPTY:
                write("</" + tag + ">")
    if elem.tail:
        write(_escape_cdata(elem.tail)) 
Example #21
Source File: merge_xml.py    From se-blender with GNU General Public License v2.0 4 votes vote down vote up
def _serialize_xml(write, elem, qnames, namespaces,
                   short_empty_elements, **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write("<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write, e, qnames, None,
                               short_empty_elements=short_empty_elements)
        else:
            write("<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (
                            k,
                            _escape_attrib(v)
                            ))

                # below is the changed line. assuming attrib is an OrderedDict this will preserve attribute order
                for k, v in elem.attrib.items():
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text:
                    write(_escape_cdata(text))
                for e in elem:
                    _serialize_xml(write, e, qnames, None,
                                   short_empty_elements=short_empty_elements)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(_escape_cdata(elem.tail)) 
Example #22
Source File: mwmbuilder.py    From se-blender with GNU General Public License v2.0 4 votes vote down vote up
def material_xml(settings, mat, file=None, node=None):
    d = data(mat)
    e = ElementTree.Element("Material", Name=mat.name)
    m = SEMaterialInfo(mat)

    def param(name, value):
        se = ElementTree.SubElement(e, 'Parameter', Name=name)
        if value:
            se.text = value

    param("Technique", _material_technique(d.technique))
    param("SpecularIntensity", _floatstr(m.specularIntensity))
    param("SpecularPower", _floatstr(m.specularPower))

    if 'GLASS' == d.technique:
        param("DiffuseColorX", '255')
        param("DiffuseColorY", '255')
        param("DiffuseColorZ", '255')
        param("GlassMaterialCCW", d.glass_material_ccw)
        param("GlassMaterialCW", d.glass_material_cw)
        param("GlassSmooth", str(d.glass_smooth))
    else:
        r, g, b = rgb(m.diffuseColor)
        param("DiffuseColorX", str(int(255 * r)))
        param("DiffuseColorY", str(int(255 * g)))
        param("DiffuseColorZ", str(int(255 * b)))

    # only for legacy materials
    if m.couldDefaultNormalTexture and not TextureType.Normal in m.images:
        m.images[TextureType.Normal] = ''

    for texType in TextureType:
        filepath = m.images.get(texType, None)
        if not filepath is None:
            derivedPath = derive_texture_path(settings, filepath)
            if (BAD_PATH.search(derivedPath)):
                settings.error("The %s texture of material '%s' exports with the non-portable path: '%s'. "
                               "Consult the documentation on texture-paths."
                               % (texType.name, mat.name, derivedPath), file=file, node=node)
            param(texType.name + "Texture", derivedPath)
        else:
            e.append(ElementTree.Comment("material has no %sTexture" % texType.name))

    return e