473,774 Members | 2,182 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,s earchTerm):
self.searchTerm =searchTerm;

def startElement(se lf,name,attrs):

if name=="HOST":
self.hostname=a ttrs.get('NAME' ,"")
self.IP=attrs.g et('IP',"")
elif name=="METRIC":
self.metricname =attrs.get('NAM E', "")
self.metricvalu e=attrs.get('VA L',"")
self.metrictype =attrs.get('TYP E',"")
self.metricunit =attrs.get('UNI TS',"")
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="HOS T"
parser=make_par ser()
curHandler=gmon dxmlparse(searc hTerm)
parser.setConte ntHandler(curHa ndler)
parser.parse(op en("/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.1 0.163" IP="192.168.10. 163" REPORTED="11936 89455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspe cified"
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 4929
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,s earchTerm):
self.searchTerm =searchTerm;

def startElement(se lf,name,attrs):

if name=="HOST":
self.hostname=a ttrs.get('NAME' ,"")
self.IP=attrs.g et('IP',"")
elif name=="METRIC":
self.metricname =attrs.get('NAM E', "")
self.metricvalu e=attrs.get('VA L',"")
self.metrictype =attrs.get('TYP E',"")
self.metricunit =attrs.get('UNI TS',"")
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="HOS T"
parser=make_par ser()
curHandler=gmon dxmlparse(searc hTerm)
parser.setConte ntHandler(curHa ndler)
parser.parse(op en("/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.1 0.163" IP="192.168.10. 163" REPORTED="11936 89455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspe cified"
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.w eb.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,s earchTerm):
self.searchTerm =searchTerm;
def startElement(se lf,name,attrs):
if name=="HOST":
self.hostname=a ttrs.get('NAME' ,"")
self.IP=attrs.g et('IP',"")
elif name=="METRIC":
self.metricname =attrs.get('NAM E', "")
self.metricvalu e=attrs.get('VA L',"")
self.metrictype =attrs.get('TYP E',"")
self.metricunit =attrs.get('UNI TS',"")
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="HOS T"
parser=make_par ser()
curHandler=gmon dxmlparse(searc hTerm)
parser.setConte ntHandler(curHa ndler)
parser.parse(op en("/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.1 0.163" IP="192.168.10. 163" REPORTED="11936 89455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspe cified"
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.w eb.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,s earchTerm):
self.searchTerm =searchTerm;
def startElement(se lf,name,attrs):
if name=="HOST":
self.hostname=a ttrs.get('NAME' ,"")
self.IP=attrs.g et('IP',"")
elif name=="METRIC":
self.metricname =attrs.get('NAM E', "")
self.metricvalu e=attrs.get('VA L',"")
self.metrictype =attrs.get('TYP E',"")
self.metricunit =attrs.get('UNI TS',"")
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="HOS T"
parser=make_par ser()
curHandler=gmon dxmlparse(searc hTerm)
parser.setConte ntHandler(curHa ndler)
parser.parse(op en("/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.1 0.163" IP="192.168.10. 163" REPORTED="11936 89455"
TN="0" TMAX="20" DMAX="0" LOCATION="unspe cified"
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
3582
by: Marian Jancar | last post by:
Hi, Is there a module for parsing spec files available? Marian -- -- Best Regards,
2
5061
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 some generic parsing module in python, in which you give some kind of grammar and callbacks ? Thanks for the help
3
3660
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 xml.sax._exceptions.SAXParseException: NCBI_Entrezgene.dtd:8:0: error in processing external entity reference This is caused by: <!DOCTYPE Entrezgene-Set PUBLIC "-//NCBI//NCBI Entrezgene/EN" "NCBI_Entrezgene.dtd">
3
1551
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 I read the file
9
4062
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" portions of Babe Ruth page (http://www.baseballprospectus.com/dt/ruthba01.shtml) and store that info in a CSV file. Also, I would like to do this for numerous players whose IDs I have stored in a text file (e.g.: cobbty01, ruthba01, speaktr01, etc.)....
4
3937
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 language that is good at parsing text to convert it into a mutt alias file. There are better ways to use Mutt with Mac's addressbook, but I want to be able to periodically convert my working addressbook file into an alias file I can then transfer...
13
4514
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 command set consisting of several single letter commands which take no arguments. A few additional single letter commands take arguments:
0
2146
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 this error and extract emails from an exchange server. First I tried: Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python24\lib\poplib.py", line 96, in __init__ raise socket.error, msg
2
3616
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 Width='10%' BGCOLOR='#c0c0c0'>Name</TH><TH width='7%' BGCOLOR='#c0c0c0'>Date</TH> and so on.... whenever I feed the parser with such file I get the error :
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.