xml and python
Harry George
hgg9140 at seanet.com
Fri Jun 2 18:13:37 EDT 2000
Install PyXML, then try this. Read the xml.dom.core for element names
and the basic functions. If you are not familiar with xml itself, see
the XML Bible. Try this routine on some known-good .xml file (I can
supply one if need be.)
I could post one I did to read/write Abiword files. My heaviest use
of python+xml is at work, gluing together a bunch of engineering apps.
Kaimar Karu <kaimar at ut.ee> writes:
> Hi,
>
> Where can I find some kind of helping material (tutorials etc) about how
> to use xml in python?
> I need some examples, just pure specification is not enough.
>
> tia,
> --
> Kaimar Karu | kaimar at ut.ee | 251 13 468
> = What a wonderful world =
>
>
#!/usr/bin/env python
#/* helloxml.py
"""
Usage: helloxml.py [options] filename
E.g., helloxml.py myfile
Options
-h,--help this message
-v,--version version
Revisions:
2000-02-23 Harry George initial version
"""
import sys,os,getopt,time,re,string,exceptions
modname="helloxml"
__version__="0.1"
def debug(ftn,txt):
sys.stdout.write(modname+'.'+ftn+':'+txt+'\n')
sys.stdout.flush()
def fatal(ftn,txt):
sys.stdout.write(modname+'.'+ftn+':FATAL:'+txt+'\n')
sys.stdout.flush()
sys.exit(1)
def usage():
print __doc__
#====================================
from xml.dom import core, utils
def main():
ftn = "main"
pargs=[] #positional args, default is empty
opts,pargs=getopt.getopt(sys.argv[1:],'hv',['help','version'])
for opt in opts:
if opt[0]=='-h' or opt[0]=='--help':
usage()
sys.exit(0)
elif opt[0]=='-v' or opt[0]=='--version':
print modname+": version="+__version__
sys.exit(0)
#---get the DOM "doc"---
if len(pargs)==0:
usage()
sys.exit(0)
filename = pargs[0]
doc = utils.FileReader( filename ).document
#---dump it out---
doc.dump();
#---convert DOM tree back to XML, and dump that
xml = doc.toxml()
print xml
#---dump the doc manually---
root=doc.get_documentElement()
mydump(root)
def mydump(node):
ftn = "mydump"
debug(ftn,"name=" +node.get_nodeName())
#---dump attributes---
attrs=node.get_attributes()
keys=attrs.keys()
for attr in keys:
debug(ftn,"attr="+attr+" value="+attrs[attr].get_nodeValue())
#---dump children---
children=node.get_childNodes()
for child in children:
#--report only elements
if child.get_nodeType()==core.ELEMENT:
mydump(child)
if __name__ == '__main__': main()
--
Harry George
hgg9140 at seanet.com
More information about the Python-list
mailing list