Thread View: pl.comp.lang.python
2 messages
2 total messages
Started by Misiek NA
Sun, 24 Jan 2010 12:35
xml.sax - problem przy parsowaniu
Author: Misiek NA
Date: Sun, 24 Jan 2010 12:35
Date: Sun, 24 Jan 2010 12:35
87 lines
3570 bytes
3570 bytes
Witam,
Napisałem program który parsuje plik XML (kod poniżej).
Format pliku XML to:
<?xml version="1.0"?>
<log>
<logentry revision="1">
<author>misiek</author>
<date>2010-01-23T21:15:01.102164Z</date>
<paths>
<path kind="" action="A">/test_1/plik.txt</path>
</paths>
<msg>- cos tam</msg>
</logentry>
</log>
Uruchamiam sktypt podając mu jako parametr plik XML i dostaję wyjątek:
KeyError: 'msg' (self.log_entry => {'date':
u'2010-01-23T21:18:01.902765Z', 'author': u'misiek', 'revision':
u'4'})
Zaglądam do pliku XML i dla revision 4 istnieje element 'msg' więc
dlaczego nie ma go w słowniku log_entry?
Czy może ktoś ma jakiś pomysł dlaczego tak się dzieje?
Pythona dopiero się uczę więc zakładam, że gdzieś popełniłem błąd:/
Wielkość przetwarzanego pliku to jakieś 36kB.
-----
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
class SvnLogHandler(ContentHandler):
def __init__(self):
self.stack = []
self.log_entry = {}
def startElement(self, name, attrs):
self.stack.append(name)
if name == u"logentry":
self.log_entry["revision"] = attrs.get(u"revision")
def endElement(self, name):
self.stack.pop()
if name == u"logentry":
try:
print "%s;%s;%s;%s;" % (self.log_entry["revision"],
self.log_entry["date"],
self.log_entry["author"], self.log_entry
["msg"].rstrip(),)
except KeyError, err:
print "KeyError: %s (self.log_entry => %s) " % (err,
str(self.log_entry),)
sys.exit(1)
self.log_entry.clear()
def characters(self, content):
name = self.stack[-1]
if name == u"author":
self.log_entry["author"] = content
elif name == u"date":
self.log_entry["date"] = content
elif name == u"msg":
self.log_entry["msg"] = content
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Uzycie: svnlog2csv.py <plik_xml>"
sys.exit(1)
parser = make_parser()
h = SvnLogHandler()
parser.setContentHandler(h)
ds = open(sys.argv[1])
parser.parse(ds)
ds.close()
--
Pozdrawiam,
M.
Re: xml.sax - problem przy parsowaniu
Author: Misiek
Date: Sun, 24 Jan 2010 18:49
Date: Sun, 24 Jan 2010 18:49
7 lines
1418 bytes
1418 bytes
OK, już nieaktualne. Przepraszam za zaśmiecanie. Następnym razem zanim wyślę coś na grupę to najpierw sobie zrobię parę minut przerwy i zerknę jeszcze raz na kod i dane wejściowe. -- Pozdrawiam, M.
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads