def toPrettyXMLFP(node, filep, ident="\t", newl="\n"):
#    try:
#        from Ft.Xml.Domlette import PrettyPrint
#        import cStringIO
#        buf = cStringIO.StringIO()
#        PrettyPrint(node, stream=buf)
#        return buf.getvalue()
#    except ImportError:
    try:
        import xml.dom.minidom
        removePrettyTextNodes(node)
        if isinstance(node, xml.dom.minidom.Attr):
            filep.write(node.nodeValue+newl)
        elif isinstance(node, xml.dom.minidom.Node):
            node.writexml(filep, "", ident, newl)
        else:
            from xml.dom.ext import PrettyPrint
            PrettyPrint(node, stream=filep)
    except ImportError:
        try:
            import Ft.Xml.cDomlette
            if isinstance(node, Ft.Xml.cDomlette.Node):
                from Ft.Xml.Lib.Print import  PrettyPrint
                PrettyPrint(node, stream=filep)
        except: 
            from xml.dom.ext import PrettyPrint
            PrettyPrint(node, stream=filep)
Ejemplo n.º 2
0
    def _get_info(self):
        doc = self.build_soap_envelope()
        PrettyPrint(doc)

        body = doc.getElementsByTagName('soap:Body')[0]

        info_request = doc.createElementNS('urn:zimbraAccount',
                                           'GetInfoRequest')
        body.appendChild(info_request)

        PrettyPrint(self._send_request(doc))
 def run(self, really=False):
     if self.xsl_file:
         _xml=StringIO.StringIO()
         PrettyPrint(self.doc, _xml)
         _doc=XmlTools.createDOMfromXML(_xml.getvalue(), self.xsl_file)
     else:
         _doc=self.doc
     
     if really:
         ecopy=ComEnterpriseCopy.getEnterpriseCopy(_doc.documentElement, _doc)
         ecopy.doAllsets()
     else:
         PrettyPrint(_doc)
Ejemplo n.º 4
0
def writePrettyXml(dom_tree, file_path):
    # Save the file in the current folder
    out_path = os.path.abspath(file_path)
    out = open(out_path, 'w')

    # Print out the result
    PrettyPrint(dom_tree, out)
Ejemplo n.º 5
0
 def checkt4(self):
     try:
         r = resolvers.NetworkResolver(['http:'])
         ps = ParsedSoap(IN, resolver=r.Resolve)
     except ParseException as e:
         print(FaultFromZSIException(e).AsSOAP(), file=OUT)
         self.fail()
     except Exception as e:
         # Faulted while processing; assume it's in the header.
         print(FaultFromException(e, 1,
                                  sys.exc_info()[2]).AsSOAP(),
               file=OUT)
         self.fail()
     print('resolving')
     typecode = TC.Struct(None, [
         TC.XML('xmltest'),
         TC.String('stringtest', resolver=r.Opaque),
     ])
     try:
         dict = ps.Parse(typecode)
     except EvaluateException as e:
         print(FaultFromZSIException(e).AsSOAP(), file=OUT)
         self.fail()
     except Exception as e:
         # Faulted while processing; now it's the body
         print(FaultFromException(e, 0,
                                  sys.exc_info()[2]).AsSOAP(),
               file=OUT)
         self.fail()
     PrettyPrint(dict['xmltest'])
     print('**', dict['stringtest'], '**')
Ejemplo n.º 6
0
def prettify_xml(xml):
    '''preserve XML formatting'''
    iostream = StringIO()
    PrettyPrint(xml, stream=iostream)
    output = iostream.getvalue()
    iostream.close()
    return output
Ejemplo n.º 7
0
    def _send_request(self, doc):
        con = HTTPSConnection(self.server)

        soapString = StringIO.StringIO()
        PrettyPrint(doc, soapString)
        soapString = soapString.getvalue()

        con.request('POST', '/service/soap', soapString)
        res = con.getresponse()
        response = res.read()
        doc = minidom.parseString(response)

        # Check for session id and change id and set them

        c = self._get_context(doc)
        e = xml.xpath.Compile('//context/sessionId/text()')
        result = e.evaluate(c)
        if len(result) > 0:
            self.session_id = (result[0]).data

        e = xml.xpath.Compile('//context/change/@token')
        result = e.evaluate(c)
        if len(result) > 0:
            self.change_id = (result[0]).value

        self._last_response = doc

        return doc
Ejemplo n.º 8
0
 def saveFile(self, _uri=None):
     if not _uri:
         _uri=self.filename
     ComLog.getLogger(__logStrLevel__).debug("file: %s" % _uri)
     stream=open(_uri,"w+")
     PrettyPrint(self.__basemodell.document, stream)
     self.filename=_uri
     self.status("save to file %s succeeded" % _uri)
     self.updateTitle(sefl.filename)
Ejemplo n.º 9
0
 def write(self, path=None):
     if not path:
         fobj = strfile()
     else:
         fobj = file(path, 'w')
     PrettyPrint(self.doc, fobj)
     if not path:
         fobj.seek(0)
         return fobj.read()
Ejemplo n.º 10
0
 def dom2str(self, xml_root=None):
     """
 This function transform a DOM tree to string.
 This function is only usefull for debugging.
 """
     xml_str = StringIO()
     PrettyPrint(xml_root, xml_str)
     xml_string = xml_str.getvalue()
     LOG('XML output: ', 0, xml_string)
     return xml_string
Ejemplo n.º 11
0
    def xmlToFile(self):
        temp = StringIO() 
        PrettyPrint(self.tester.summaryDocument.documentElement, temp)

        of = open(self.RTTSummary, 'w')        
        of.write(temp.getvalue())
        # of.write(self.tester.summaryDocument.toprettyxml('   '))
        # of.write(self.tester.summaryDocument.toprettyxml('   ','\n'))
        # of.write(self.tester.summaryDocument.toxml('utf-8'))
        of.close
    def serialize_to_file(self, fname):
        if not self.enabled: return
        from xml.dom.ext import PrettyPrint

        if isinstance(fname, basestring):
            outfn = open(fname, "w")
        else:
            outfn = fname
        PrettyPrint(self.doc, outfn)
        if isinstance(fname, basestring):
            outfn.close()
Ejemplo n.º 13
0
def writeXmlFile(dom_tree, file_name='feeds_to_import.xml'):

  # Save the file in the current folder
  out_file = os.path.join('./', file_name)
  out_path = os.path.abspath(out_file)
  out = open(out_path, 'w')

  # Print out the result
  out.write('<?xml version="1.0" encoding="UTF-8"?>')
  PrettyPrint(dom_tree, out)
  return out_file
def main():
    #    ComLog.setLevel(logging.INFO)
    print "Testing HP_Object..."
    print "Creating an HP_EVA"
    eva = Test_HP_EVA_Storagecell_HSV110()
    print "Eva: %s" % (eva)
    print "Adding a Vdisk to the eva..."
    vdisk = HP_EVA_Virtualdisk(objectid="DC200".ljust(34, "F") + "1",
                               objectname="vdisk1")
    eva.addVdisk(vdisk)
    print "Eva:"
    print eva
    print "Vdisk:"
    print vdisk
    print "In XML: "
    from xml.dom.ext import PrettyPrint
    print "Eva:"
    PrettyPrint(eva.toXML())
    print "Vdisk:"
    PrettyPrint(vdisk.toXML())
    print "Delete Vdisk:"
    eva.delVdisk(vdisk)
    print "Eva:"
    PrettyPrint(eva.toXML())

    testHP_ObjectFromXML("./test/system_dump.xml")
    testHP_ObjectFromXML("./test/vdisk_dump.xml")
    testHP_ObjectFromXML("./test/snapshot_dump.xml")
    testHP_ObjectFromXML("./test/diskgroup_dump.xml")
    testHP_ObjectFromXML("./test/lun_dump.xml")
    testHP_ObjectFromXML("./test/presentations_dump.xml", False)
    print "Testing factory via map:"
    vdisk = HP_EVA_Object(classtype="vdisk",
                          objectid="DC200".ljust(34, "F") + "2",
                          objectname="vdisk2")
    print "Vdisk:"
    print vdisk
    param = "objectid"
    print "hasattr(%s): %s" % (param, hasattr(vdisk, param))
    print "getattr(%s): %s" % (param, getattr(vdisk, param))
    print "Objectid: " + vdisk.objectid
Ejemplo n.º 15
0
def format_xml(xml_string):
    if xml_string:
        reader = Sax2.Reader()
        doc = reader.fromString(xml_string)
        doc.normalize()
        f = StringIO.StringIO()
        PrettyPrint(doc, f)
        f.seek(0,0)
        formated_xml = f.read().decode('utf-8')
        return formated_xml
    else:
        return ''
Ejemplo n.º 16
0
def _stringify(tree, pretty):
    """
    Turn an ElementTree into a string, optionally with line breaks and indentation.
    """

    if pretty and feedformatterCanPrettyPrint:
        string = StringIO()
        doc = FromXml(ET.tostring(tree))
        PrettyPrint(doc, string, indent="    ")
        return string.getvalue()
    else:
        return ET.tostring(tree)
Ejemplo n.º 17
0
    def write(self, filehandle, format='xml'):
        """
        Write the GRL in the specified format to the file object.

        *filehandle*: file

        *format*: str
        """
        if format == 'xml':
            root = ET.Element('LumiRangeCollection')
            subroot = ET.SubElement(root, 'NamedLumiRange')
            name = ET.SubElement(subroot, 'Name')
            name.text = self.name
            version = ET.SubElement(subroot, 'Version')
            version.text = self.version
            for meta in self.metadata:
                subroot.append(meta)
            for run in self.iterruns():
                lumiblocks = self.__grl[run]
                lbcol = ET.SubElement(subroot, 'LumiBlockCollection')
                runelement = ET.SubElement(lbcol, 'Run')
                runelement.text = str(run)
                for lumiblock in lumiblocks:
                    lbrange = ET.SubElement(lbcol, 'LBRange')
                    lbrange.set('Start', str(lumiblock[0]))
                    lbrange.set('End', str(lumiblock[1]))
            date = datetime.datetime.now().strftime("%Y-%m-%d at %H:%M:%S")
            meta = (
                '''<!DOCTYPE LumiRangeCollection SYSTEM '''
                '''"http://atlas-runquery.cern.ch/LumiRangeCollection.dtd">\n'''
                '''<!-- This document was created by goodruns: '''
                '''http://pypi.python.org/pypi/goodruns/ on %s -->\n''' % date)
            tree = ET.ElementTree(root)
            if USE_LXML:
                filehandle.write('<?xml version="1.0"?>\n')
                filehandle.write(meta)
                tree.write(filehandle, pretty_print=True)
            else:
                # get pretty XML from ElementTree
                xml = minidom.parseString(meta +
                                          ET.tostring(tree.getroot(), 'utf-8'))
                PrettyPrint(xml, stream=filehandle, encoding='utf-8')
        elif format in ('yml', 'yaml'):
            filehandle.write(yaml.dump(self.to_dict()))
        elif format == 'txt':
            filehandle.write(str(self) + '\n')
        elif format in ('py', 'python'):
            filehandle.write("grl = ")
            pprint(self.__grl, stream=filehandle)
        elif format == 'cut':
            filehandle.write(self.cut() + '\n')
        else:
            raise ValueError("Unrecognized grl format")
Ejemplo n.º 18
0
	def __change(self,file_conf,node,value):
		from xml.dom.minidom import parse
		from xml.dom.ext import PrettyPrint
		doc = parse(file_conf)
		node = doc.getElementsByTagName(node)[0]
		child = node.childNodes
		if len(child) != 0:
			child[0].data=value
		else:
			node.appendChild(doc.createTextNode(value))
      		doc_conf=open(file_conf,"w")
		PrettyPrint(doc,doc_conf)
		doc_conf.close()
Ejemplo n.º 19
0
Archivo: bml.py Proyecto: hfs/txt2blink
 def write(self, writer):
     impl = getDOMImplementation()
     doctype = impl.createDocumentType(
         "bml", None, "http://www.blinkenlights.de/dtd/bml.dtd")
     doc = impl.createDocument(None, "blm", doctype)
     root = doc.documentElement
     root.attributes['width'] = str(self.width)
     root.attributes['height'] = str(self.height)
     root.attributes['bits'] = str(self.bits)
     root.attributes['channels'] = str(self.channels)
     self.addHeader(doc)
     self.addFrames(doc)
     PrettyPrint(doc, writer, indent="\t", encoding="utf-8")
def _stringify(tree, pretty):
    """
    Turn an ElementTree into a string, optionally with line breaks and indentation.
    """

    if pretty and CAN_PRETTY_PRINT:
        string = StringIO()
        doc = FromXml(_element_to_string(tree))
        PrettyPrint(doc, string, indent="    ")

        return string.getvalue()
    else:
        return _element_to_string(tree)
 def pretty_print(self, text):
     """ Pretty print the XML.
     
     """
     from xml.dom.ext import PrettyPrint
     
     dom = self.get_dom(text)
     
     stream = self.StringIO()
     PrettyPrint(dom, stream)
     
     dom.unlink()
     
     return stream.getvalue()
def testHP_ObjectFromXML(filename, xml=True):
    from xml.dom.ext.reader import Sax2
    from xml.dom.ext import PrettyPrint
    reader = Sax2.Reader(validate=0)
    xml_dump = open(filename, "r")
    print "From XML(%s):" % (filename)
    document = reader.fromStream(xml_dump)
    xml_dump.close()
    print "The HP_Oject:"
    result = HP_EVA_Object.fromXML(document.documentElement)
    print "Class: %s" % (result.__class__)
    if xml:
        PrettyPrint(result.toXML())
    else:
        print result
    return result
Ejemplo n.º 23
0
class XML_Generator(object):
    _logger = logging.getLogger('XML_Generator')

    def __init__(self, template, nsmap=None):
        self.root = etree.fromstring(template)
        self.nsmap = nsmap

    # end def __init__

    def generate(self, **scope_dict):
        if self.nsmap:
            root = etree.Element(self.root.tag,
                                 self.root.attrib,
                                 nsmap=self.nsmap)
        else:
            root = etree.Element(self.root.tag, self.root.attrib)
        self.out = etree.ElementTree(root)
        self._iterate(self.root, root, scope_dict)
        return self.out

    # end def generate

    def write(self, xml_file, pretty=True):
        from xml.dom.ext import PrettyPrint
        from xml.dom.ext.reader.Sax import FromXmlFile

        try:
            f = open(xml_file, "w")
            try:
                self.out.write(f)
            finally:
                f.close()
        except (SystemExit, KeyboardInterrupt), exc:
            raise

        if pretty:
            doc = FromXmlFile(xml_file)
            try:
                f = open(xml_file, "w")
                try:
                    PrettyPrint(doc, f)
                finally:
                    f.close()
            except (SystemExit, KeyboardInterrupt), exc:
                raise
Ejemplo n.º 24
0
 def get_xml(self):
     'Build XML form DOM.'
     xml = b''
     if self.dom:
         self.dom.normalize()
         #if PrettyPrint:
         # (PrettyPrint is disabled be cause of wrong result: "&lt;value>")
         if 0:
             f = io.StringIO()
             PrettyPrint(self.dom, f, self.encoding)
             f.seek(0, 0)
             xml = f.read()
         else:
             # Kdyz chybi funkce PrettyPrint()
             #xml = self.dom.toprettyxml('', '', self.encoding)
             xml = self.dom.toxml(self.encoding)
     # hook parametru standalone
     return re.sub(b'(<?xml .+?)\?>', b'\\1 standalone="no"?>', xml, re.I)
Ejemplo n.º 25
0
 def ls(self, type, rest):
     #        params=rest.split("\s+")
     params = self.parseParams(rest)
     #mylogger.debug("Params: %s" %(params))
     if self.selected_system:
         if len(params) == 0:
             ComLog.getLogger().debug(
                 "ls(%s %s), %s: %s" %
                 (type, rest, type,
                  self.selected_system.getTransient(type)))
             self.stdout.write(self.CMD_OUTPUT["ls_all"] % (type, "\n".join(
                 self.selected_system.getTransient(type).names())))
             return 0
         elif len(params) == 1:
             ComLog.getLogger().debug(
                 "ls(%s %s), %s<%s>: %s" %
                 (type, params[0], type,
                  self.selected_system.getTransient(type).__class__,
                  self.selected_system.getTransient(type)))
             self.stdout.write(
                 self.CMD_OUTPUT["ls"] %
                 (params[0], self.selected_system.getTransient(type).get(
                     params[0])))
             return 0
         elif len(params) == 2 and params[1] == "xml":
             import StringIO
             from xml.dom.ext import PrettyPrint
             ComLog.getLogger().debug(
                 "ls(%s %s), %s<%s>: %s" %
                 (type, params[0], type,
                  self.selected_system.getTransient(type).__class__,
                  self.selected_system.getTransient(type)))
             buffer = StringIO.StringIO()
             PrettyPrint(
                 self.selected_system.getTransient(type).get(
                     params[0]).toXML(), buffer)
             self.stdout.write(self.CMD_OUTPUT["ls"] %
                               (params[0], buffer.getvalue()))
             buffer.close()
             return 0
         else:
             raise SyntaxSSSUError("^".rjust(len(self.prompt) + len("ls")))
     else:
         raise NoSystemSelected()
Ejemplo n.º 26
0
    def write(self, tstore):
        """
        Writes a Qt TS file.

        @param tstore: The UT3 translation store with the items to be written.
        """

        if not isinstance(tstore, UT3Store):
            raise TypeError

        if self.__name is not None:
            # check if the file is writable
            if not os.access(os.path.dirname(self.__name), os.W_OK):
                support.print_error_message("PO file not writable")
                sys.exit()
            out = file(self.__name, 'w')
        else:
            out = sys.stdout

        impl = xml.dom.getDOMImplementation()
        doctype = impl.createDocumentType('TS', None, None)
        doc = impl.createDocument(None, "TS", doctype)
        root = doc.documentElement

        source_list = tstore.get_sources()
        if len(source_list) == 0:
            context_entries = tstore.get_by_source("")
            root.appendChild(
                _generate_context_element(doc, "", context_entries))
        else:
            for context_name in source_list:
                context_entries = tstore.get_by_source(context_name)
                root.appendChild(
                    _generate_context_element(doc, context_name,
                                              context_entries))

        PrettyPrint(root, out)

        if not self.__name is None:
            out.close()

        doc.unlink()

        return
Ejemplo n.º 27
0
    def toMathml(self, out=None, indent=False):
        """Convert this MathDOM into MathML and write it to file (or
        file-like object) out.  Pretty printing is activated by
        setting indent=True."""
        if out is None:
            out = sys.stdout

        root = self._document.lastChild
        if root and root.localName != u'math':
            dom = getDOMImplementation()
            document = dom.createDocument(MATHML_NAMESPACE_URI, u"math", None)
            document.lastChild.children[:] = [root]
        else:
            document = self._document

        if indent:
            PrettyPrint(document, out)
        else:
            Print(document, out)
Ejemplo n.º 28
0
 def to_xml_stream(self,
                   stream,
                   pretty=True,
                   indent='  ',
                   encoding='UTF-8',
                   **kwargs):
     '''Dump object to a file object like stream.'''
     close = False
     if isinstance(stream, basestring):
         close = True
         if _xmldomext: stream = file(stream, 'w')
         else:
             stream = codecs.open(stream,
                                  mode='w',
                                  encoding=encoding,
                                  errors='replace')
     try:
         e = self.to_xml_elt(**kwargs)
         if pretty:
             if _xmldomext:
                 PrettyPrint(Sax2.Reader().fromString(
                     ElementTree.tostring(e)),
                             stream=stream,
                             encoding=encoding,
                             indent=indent,
                             preserveElements=None)
             else:
                 #                    minidom.parseString(
                 #                        ElementTree.tostring(e)).writexml(
                 #                            stream, addindent=indent, newl='\n')
                 pretty_indent(e)
                 stream.write(ElementTree.tostring(e))
         else:
             d = ElementTree.ElementTree(e)
             #d.write(stream, xml_declaration=True, method="xml")
             d.write(stream,
                     encoding=encoding,
                     xml_declaration=True,
                     method="xml")
     finally:
         if close: stream.close()
     return e
Ejemplo n.º 29
0
    def element_extract(self, astr_tag, astr_value, ab_removeElement=0):
        #
        # PRECONDITIONS
        # o str_tag is a tag name to search for
        # o str_value is the value of the tag to extract
        #
        # POSTCONDITIONS
        # 	- element_extract('idCode', 'LSP-001')
        #	  will extract the node (and its children) containing
        #	  an 'idCode' of 'LSP-001'
        #	- if <ab_removeElement>, then the dbChild containing the
        #	  target tag value is removed from the database.
        #

        b_targetFound = 0
        for database in self.mXMLdoc.childNodes:
            for dbChild in database.childNodes:
                for record in dbChild.childNodes:
                    if record.nodeType == record.ELEMENT_NODE:
                        str_tag = record.tagName
                        for value in record.childNodes:
                            if value.nodeType == value.TEXT_NODE:
                                str_data = value.data
                        self.mdict_element[str_tag] = str_data
                        if str_tag == astr_tag and str_data == astr_value:
                            b_targetFound = 1
                if b_targetFound:
                    for key in self.mC_struct.ml_keys:
                        self.mC_struct.mdict_sgmlCore[key].value_set(
                            self.mdict_element[key])
                    if ab_removeElement:
                        database.removeChild(dbChild)
                        str_edittedDBName = "%s.edt" % self.mstr_XMLfile
                        file_edittedDBName = open(str_edittedDBName, 'w')
                        PrettyPrint(self.mXMLdoc, file_edittedDBName)
                    return b_targetFound
        return b_targetFound
Ejemplo n.º 30
0
        def toXml(self, filename='', compress=False):
            """drawing.toXml()        ---->to the screen
            drawing.toXml(filename)---->to the file
            writes a svg drawing to the screen or to a file
            compresses if filename ends with svgz or if compress is true
            """
            doctype = implementation.createDocumentType(
                'svg', "-//W3C//DTD SVG 1.0//EN""", 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd ')

            global root
            # root is defined global so it can be used by the appender. Its also possible to use it as an arugument but
            # that is a bit messy.
            root = implementation.createDocument(None, None, doctype)
            # Create the xml document.
            global appender

            def appender(element, elementroot):
                """This recursive function appends elements to an element and sets the attributes
                and type. It stops when alle elements have been appended"""
                if element.namespace:
                    e = root.createElementNS(element.namespace, element.type)
                else:
                    e = root.createElement(element.type)
                if element.text:
                    textnode = root.createTextNode(element.text)
                    e.appendChild(textnode)
                # in element.attributes is supported from python 2.2
                for attribute in list(element.attributes.keys()):
                    e.setAttribute(
                        attribute, str(element.attributes[attribute]))
                if element.elements:
                    for el in element.elements:
                        e = appender(el, e)
                elementroot.appendChild(e)
                return elementroot
            root = appender(self.svg, root)
            if not filename:
                xml = StringIO()
                PrettyPrint(root, xml)
                if compress:
                    import gzip
                    f = StringIO()
                    zf = gzip.GzipFile(fileobj=f, mode='wb')
                    zf.write(xml.getvalue())
                    zf.close()
                    f.seek(0)
                    return f.read()
                else:
                    return xml.getvalue()
            else:
                try:
                    if filename[-4:] == 'svgz':
                        import gzip
                        xml = StringIO()
                        PrettyPrint(root, xml)
                        f = gzip.GzipFile(
                            filename=filename, mode='wb', compresslevel=9)
                        f.write(xml.getvalue())
                        f.close()
                    else:
                        f = open(filename, 'w')
                        PrettyPrint(root, f)
                        f.close()
                except:
                    print("Cannot write SVG file: " + filename)