[XML-SIG] newbie question
Mike Olson
Mike.Olson@fourthought.com
Thu, 17 May 2001 16:18:52 -0600
Chris Meyers wrote:
>
> Ok I have been looking at PyXML for a couple of days now, and I still can't really find a good example of the basic stuff I need to do. I want to read in an XML file, traverse the tree and pull out information. For example I would like to go through this xml:
>
> <?xml version="1.0" encoding="UTF-8"?>
> <report>
> <data>
> <rec>
> <fld id="1">123</fld>
> <fld id="2">John></fld>
> <fld id="3">Smith></fld>
> </rec>
> </data>
> </report>
There are a couple of ways:
1. Use DOM
from xml.dom.ext.reader import PyExpat
reader = PyExpat.Reader()
dom = reader.fromString(XML_SRC)
flds = dom.documentElement.getElementsByTagName('fld')
for f in flds:
print fld.getAttribute('id')
print fld.firstChild.data
2. Use XPath
from xml import xpath
from xml.dom.ext.reader import PyExpat
reader = PyExpat.Reader()
dom = reader.fromString(XML_SRC)
flds = xpath.Evaluate('//fld',contextNode = dom)
for f in flds:
print fld.getAttribute('id')
print fld.firstChild.data
Mike
>
> >From this xml I would like to pull out the id attributes and the values from the <fld> elements. I can do this in jython with jdom easily enough, but I need to use python for my current application
>
> If someone could point me in the right direction as to where to look to find an example similar to what I am trying to do, I would really appreciate it.
>
> Thanks,
> Chris
>
> _______________________________________________
> XML-SIG maillist - XML-SIG@python.org
> http://mail.python.org/mailman/listinfo/xml-sig
--
Mike Olson Principal Consultant
mike.olson@fourthought.com (303)583-9900 x 102
Fourthought, Inc. http://Fourthought.com
Software-engineering, knowledge-management, XML, CORBA, Linux, Python