msxml3 and IStream interface

jj jj at void.si
Fri Dec 29 06:52:58 EST 2000


Hi,
I want to use MSXML3 library for writing xml in file, but I dont know how to
implement IStream interface in acceptable way. In following source is
stripped Stream class from python examples. Too prove that all other code is
working there is working example of saving in COM structured document file.
I would also appreciate comments about my coding, especially how to get
another interface pointer from object. I found only working solution using
king of import typelib with makepy.py utility.

Regars, JJ

# example ###################################################

import win32com.client, os
import pythoncom, msxml_TLB
#msxml_TLB: makepy.py -o msxml_TLB.py "Microsoft XML, v3.0"

class Stream:
 '''from examples, but it is not working well, btw it is sptripped version
juto to prove bug'''
 _public_methods_ = [ 'Read', 'Write']
 _com_interfaces_ = [ pythoncom.IID_IStream ]

 def Read(self, amount): return 0
 def Write(self, data): return 0

class SaxWriter: #wrapper around xmlwriter
 def __init__(self):
  self.elements = []
  self.wr = win32com.client.Dispatch("Msxml2.MXXMLWriter")
  # !!! reason for importing typelibrary, could be done without importing
typelib !!!!
  self.ch =msxml_TLB.IVBSAXContentHandler(self.wr)
  self.atrs = win32com.client.Dispatch("Msxml2.SAXAttributes")

 def startDocument(self):
  self.ch.startDocument()

 def startElement(self,name):
  self.ch.startElement("", "", name, self.atrs)
  self.atrs.clear()
  self.elements.append(name)

 def addAttr(self, atr, value):
  self.atrs.addAttribute("", "", atr, "", value)

 def endElement(self):
  self.ch.endElement("", "", self.elements.pop())

 def characterData(self, s):
  self.ch.characters(s)

 def endDocument(self):
  self.ch.endDocument()

strg=None
def STRG(fname):
 os.unlink(fname)
 global strg
 strg=pythoncom.StgCreateDocfile(fname, 0x12, 0)
 return strg.CreateStream('a', 0x12, 0, 0)

def test():
 s = SaxWriter()
 st = Stream()  # !!!! its not working
 #st =STRG('c:/tmp/strg.txt')  # this is working
 s.wr.output= st
 s.startDocument()
 s.addAttr("cover", "hard")
 s.startElement("book")
 s.characterData("kedf < sdf > dfgl sdfglj sdlfkgj ")
 s.startElement("book1")
 s.characterData("nested element")
 s.endElement()
 s.endElement()
 s.endDocument()
 #print s.wr.output
 global strg
 del strg

test()





More information about the Python-list mailing list