473,230 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,230 software developers and data experts.

Parsing xml file in python

I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
The txt contains null elements. Any reason what iam doing wrong here
Here is the code that i wrote

import sys,os
import xml.sax
import xml.sax.handler
from xml.sax.handler import ContentHandler
from xml.sax import make_parser

class gmondxmlparse (ContentHandler):

def __init__(self,searchTerm):
self.searchTerm=searchTerm;

def startElement(self,name,attrs):

if name=="HOST":
self.hostname=attrs.get('NAME',"")
self.IP=attrs.get('IP',"")
elif name=="METRIC":
self.metricname=attrs.get('NAME', "")
self.metricvalue=attrs.get('VAL',"")
self.metrictype=attrs.get('TYPE',"")
self.metricunit=attrs.get('UNITS',"")
return

def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
fh.write("the ip address is", self.IP, "\n")
fh.close()

searchTerm="HOST"
parser=make_parser()
curHandler=gmondxmlparse(searchTerm)
parser.setContentHandler(curHandler)
parser.parse(open("/root/yhpc-2.0/gmond.xml"))
Here is the sample of xml file

Here is the xmk file called gmond.xml
<HOST NAME="192.168.10.163" IP="192.168.10.163" REPORTED="1193689455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
GMOND_STARTED="1193170061">
<METRIC NAME="cpu_num" VAL="2" TYPE="uint16" UNITS="CPUs" TN="994"
TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>

Oct 30 '07 #1
5 4904
am******@gmail.com schrieb:
I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
The txt contains null elements. Any reason what iam doing wrong here
Here is the code that i wrote

import sys,os
import xml.sax
import xml.sax.handler
from xml.sax.handler import ContentHandler
from xml.sax import make_parser

class gmondxmlparse (ContentHandler):

def __init__(self,searchTerm):
self.searchTerm=searchTerm;

def startElement(self,name,attrs):

if name=="HOST":
self.hostname=attrs.get('NAME',"")
self.IP=attrs.get('IP',"")
elif name=="METRIC":
self.metricname=attrs.get('NAME', "")
self.metricvalue=attrs.get('VAL',"")
self.metrictype=attrs.get('TYPE',"")
self.metricunit=attrs.get('UNITS',"")
return

def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
fh.write("the ip address is", self.IP, "\n")
fh.close()

searchTerm="HOST"
parser=make_parser()
curHandler=gmondxmlparse(searchTerm)
parser.setContentHandler(curHandler)
parser.parse(open("/root/yhpc-2.0/gmond.xml"))
Here is the sample of xml file

Here is the xmk file called gmond.xml
<HOST NAME="192.168.10.163" IP="192.168.10.163" REPORTED="1193689455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
GMOND_STARTED="1193170061">
<METRIC NAME="cpu_num" VAL="2" TYPE="uint16" UNITS="CPUs" TN="994"
TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
Without an actual error given, it's hard to know what your problem is.

One thing though is noticable: your XML below isn't valid - XML has only
one root-element.

And just for the record: it appears that you work under linux using a
root-account. Bad idea. Really.

http://linuxbraindump.org/2007/08/13...w-linux-users/

Diez
Oct 30 '07 #2
That XML is just a snapshot
I am not getting into the xml parser. The error is not generated but
also the /root/yhpc-2.0/ganglia.txt does not contain anything.


On Oct 30, 12:32 pm, "Diez B. Roggisch" <de...@nospam.web.dewrote:
amjad...@gmail.com schrieb:
I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
The txt contains null elements. Any reason what iam doing wrong here
Here is the code that i wrote
import sys,os
import xml.sax
import xml.sax.handler
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
class gmondxmlparse (ContentHandler):
def __init__(self,searchTerm):
self.searchTerm=searchTerm;
def startElement(self,name,attrs):
if name=="HOST":
self.hostname=attrs.get('NAME',"")
self.IP=attrs.get('IP',"")
elif name=="METRIC":
self.metricname=attrs.get('NAME', "")
self.metricvalue=attrs.get('VAL',"")
self.metrictype=attrs.get('TYPE',"")
self.metricunit=attrs.get('UNITS',"")
return
def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
fh.write("the ip address is", self.IP, "\n")
fh.close()
searchTerm="HOST"
parser=make_parser()
curHandler=gmondxmlparse(searchTerm)
parser.setContentHandler(curHandler)
parser.parse(open("/root/yhpc-2.0/gmond.xml"))
Here is the sample of xml file
Here is the xmk file called gmond.xml
<HOST NAME="192.168.10.163" IP="192.168.10.163" REPORTED="1193689455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
GMOND_STARTED="1193170061">
<METRIC NAME="cpu_num" VAL="2" TYPE="uint16" UNITS="CPUs" TN="994"
TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>

Without an actual error given, it's hard to know what your problem is.

One thing though is noticable: your XML below isn't valid - XML has only
one root-element.

And just for the record: it appears that you work under linux using a
root-account. Bad idea. Really.

http://linuxbraindump.org/2007/08/13...s-for-new-linu...

Diez

Oct 30 '07 #3
On Tue, 30 Oct 2007 11:45:17 -0700, amjadcsu wrote:
I am not getting into the xml parser.
What does this mean!?
The error is not generated but also the /root/yhpc-2.0/ganglia.txt does
not contain anything.
Maybe because…
def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
…this line will raise an exception. `file.write()` takes just one
argument, not three as in this call. If you don't get an exception maybe
you have other places with a bare ``except`` like in the snippet above.
Don't do that. Catch the specific exception you want to handle with an
``except`` and not simply *all*.

Ciao,
Marc 'BlackJack' Rintsch
Oct 30 '07 #4
On Tue, Oct 30, 2007 at 11:45:17AM -0700, am******@gmail.com wrote regarding Re: Parsing xml file in python:

Top-posting corrected....
>
On Oct 30, 12:32 pm, "Diez B. Roggisch" <de...@nospam.web.dewrote:
amjad...@gmail.com schrieb:
I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
The txt contains null elements. Any reason what iam doing wrong here
Here is the code that i wrote
import sys,os
import xml.sax
import xml.sax.handler
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
class gmondxmlparse (ContentHandler):
def __init__(self,searchTerm):
self.searchTerm=searchTerm;
def startElement(self,name,attrs):
if name=="HOST":
self.hostname=attrs.get('NAME',"")
self.IP=attrs.get('IP',"")
elif name=="METRIC":
self.metricname=attrs.get('NAME', "")
self.metricvalue=attrs.get('VAL',"")
self.metrictype=attrs.get('TYPE',"")
self.metricunit=attrs.get('UNITS',"")
return
def endElement(self,name):
if name=="HOST" and self.searchTerm==self.hostname:
try:
fh=open('/root/yhpc-2.0/ganglia.txt' ,'w')
except:
print "File /root/yhpc-2.0/ganglia.txt can not be
open"
sys.exit(1)
fh.write("This is a test for xml parsing with python with
chris and amjad \n")
fh.write("the host name is", self.hostname, "\n")
fh.write("the ip address is", self.IP, "\n")
fh.close()
searchTerm="HOST"
parser=make_parser()
curHandler=gmondxmlparse(searchTerm)
parser.setContentHandler(curHandler)
parser.parse(open("/root/yhpc-2.0/gmond.xml"))
Here is the sample of xml file
Here is the xmk file called gmond.xml
<HOST NAME="192.168.10.163" IP="192.168.10.163" REPORTED="1193689455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspecified"
GMOND_STARTED="1193170061">
<METRIC NAME="cpu_num" VAL="2" TYPE="uint16" UNITS="CPUs" TN="994"
TMAX="1200" DMAX="0" SLOPE="zero" SOURCE="gmond"/>
Without an actual error given, it's hard to know what your problem is.

One thing though is noticable: your XML below isn't valid - XML has only
one root-element.

And just for the record: it appears that you work under linux using a
root-account. Bad idea. Really.

http://linuxbraindump.org/2007/08/13...s-for-new-linu...

Diez


That XML is just a snapshot
I am not getting into the xml parser. The error is not generated but
also the /root/yhpc-2.0/ganglia.txt does not contain anything.
Well, if ganglia.txt contains nothing, and you received no output from the program, then either endElement never got called, or `if name=="HOST" and self.searchTerm==self.hostname:` never evaluated to true. Because if you couldn't open for writing, you would have gotten the message you set up on the except block, and if you could, then even if your variables didn't contain any data, you would have seen the boilerplate text that you wrote.

Cheers,
Cliff

P.S. Please bottom-post when replying to the python list. It sucks to have to look up and down a thread to see what's been said.

Oct 30 '07 #5
am******@gmail.com wrote:
I am a newbie in python
I am trying to parse a xml file and write its content in a txt file.
If you want to write code that does not hide your bugs behind cryptic event
handlers and instead helps you get XML work done, try using ElementTree or
lxml instead of SAX. The first is in the standard library of Python 2.5, the
second is here:

http://codespeak.net/lxml

Stefan
Oct 30 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Marian Jancar | last post by:
Hi, Is there a module for parsing spec files available? Marian -- -- Best Regards,
2
by: Boris Boutillier | last post by:
Hi all, I'm looking for parsing a Verilog file in my python module, is there already such a tool in python (a module in progress) to help instead of doing a duplicate job. And do you know of...
3
by: Willem Ligtenberg | last post by:
I decided to use SAX to parse my xml file. But the parser crashes on: File "/usr/lib/python2.3/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception...
3
by: Gregor Horvath | last post by:
Hi, given the dynamic nature of python I assume that there is an elegant solution for my problem, but I did not manage to find it. I have a file that contains for example on line: when...
9
by: ankitdesai | last post by:
I would like to parse a couple of tables within an individual player's SHTML page. For example, I would like to get the "Actual Pitching Statistics" and the "Translated Pitching Statistics"...
4
by: R Wood | last post by:
Greetings - A recent Perl experiment hasn't turned out so well, which has piqued my interest in Python. The project is this: take a Vcard file exported from Apple's Addressbook and use a...
13
by: Chris Carlen | last post by:
Hi: Having completed enough serial driver code for a TMS320F2812 microcontroller to talk to a terminal, I am now trying different approaches to command interpretation. I have a very simple...
0
by: Ahmed, Shakir | last post by:
Thanks everyone who tried to help me to parse incoming email from an exchange server: Now, I am getting following error; I am not sure where I am doing wrong. I appreciate any help how to resolve...
2
by: Felipe De Bene | last post by:
I'm having problems parsing an HTML file with the following syntax : <TABLE cellspacing=0 cellpadding=0 ALIGN=CENTER BORDER=1 width='100%'> <TH BGCOLOR='#c0c0c0' Width='3%'>User ID</TH> <TH...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.