By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,383 Members | 2,070 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,383 IT Pros & Developers. It's quick & easy.

Use python to process XML file

P: n/a
Hi,
Can you please tell me how Use python to process XML file?
The example I find is build a DOM, but I just need to do it in SAX
based, how can I do that?

For example, I have a xml file like this:
<log>
<a> text </a>
<a> text </a>
<b> text </b>
<a> text </a>
<c> text </c>
<a> text </a>
<b> text </b>
</log>

For i want to process the node in the order they appears.
If element name == 'a'
do this
else If element name == 'b'
do this
else If element name == 'c'
do this

Mar 10 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
si***************@gmail.com:
Can you please tell me how Use python to process XML file?
The example I find is build a DOM, but I just need to do it in SAX
based, how can I do that?


http://docs.python.org/lib/module-xml.sax.html
http://pyxml.sourceforge.net/topics/...ction-SAX.html

--
René Pijlman
Mar 10 '06 #2

P: n/a
you can use function parse from xml.sax
It takes your xml as the first argument and an
xml.sax.handler.ContentHandler instance as the second.
---
from xml.sax import parse
from xml.sax.handler import ContentHandler

class LogHandler(ContentHandler):
def startElement(self,name):
if name=='a':
#self.do_this()

parse(xmlLog.xml,LogHandler())

Mar 10 '06 #3

P: n/a
I have a little py module that implements the Composite pattern to
represent xml file contents. My class is called ExtensionRegistry
because that's what I use it for, you could rename it to whatever you
wanted. After parsing, this allows me to access my xml file contents
like this:

xmlFile = ExtensionRegistry(xmlFile = 'test.xml')

print xmlFile['log']['a'].getDataItems()

would result in printing
text


Let me know if you want me to send it to you.

Mar 10 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.