[XML-SIG] Beginner XML-Question
tpassin@home.com
tpassin@home.com
Thu, 27 Jul 2000 23:46:31 -0400
Manfred Weber" asked
>I am absolut beginner...to Python..
>could anyone just send me a simple PythonScript using the xmlLib...
Is this simple enough?
1) Create a file "test.xml" containing your xml example.
2) Run xmllib against it (this is on Win95)(python must be on your path or
be run from a batch file):
D:>python "c:\Program Files\Python\Lib\xmllib.py" test.xml
The output:
start tag: <collection>
data: '\012 '
start tag: <comic title="Sandman" number="62" >
data: '\012 '
start tag: <writer>
data: 'Neil Gaiman'
end tag: </writer>
data: '\012 '
start tag: <penciller pages="1-9,18-24" >
data: 'Glyn Dillon'
end tag: </penciller>
data: '\012 '
start tag: <penciller pages="10-17" >
data: 'Charles Vess'
end tag: </penciller>
data: '\012 '
end tag: </comic>
data: '\012'
end tag: </collection>
data: '\012 \012'
Here is another simple program (not using your data):
"""
bare.py - Demonstrate handling specifically-named elements using xmllib
"""
import xmllib
class bareBones(xmllib.XMLParser):
def __init__(self):
xmllib.XMLParser.__init__(self)
# Report start of element <specialTag>
def start_specialTag(self, attrs):
print "Start specialTag"
print "element attributes:", attrs
self.handle_data=self.do_data # use our data handler to handle the
content
# Report reaching </specialTag>
def end_specialTag(self):
print "End specialTag"
self.handle_data=self.null_data # reset the data handler
# A minimal data handler
def do_data(self,data):
print "===============\n",data,"\n==============="
def null_data(self,data):pass
doc=\
"""<?xml version="1.0"?>
<doc>
<e1>This element won't be reported</e1>
<specialTag a="attribute 1">This one will</specialTag>
</doc>
"""
if __name__=="__main__":
parser=bareBones()
parser.feed(doc)
parser.close()
I'm running version 0.2 of xmllib, which came with my Python 1.5.2
distribution.
Cheers,
Tom Passin
>Lets say I use this xml-example:
<collection>
<comic title="Sandman" number='62'>
<writer>Neil Gaiman</writer>
<penciller pages='1-9,18-24'>Glyn Dillon</penciller>
<penciller pages="10-17">Charles Vess</penciller>
</comic>
</collection>
?A very simple script that prints out any element (f.e. the writer) would do
it!