Python and XML Help

Scott David Daniels Scott.Daniels at Acm.Org
Wed Apr 15 18:43:37 CEST 2009


ookrin wrote:
> .... I am still learning. And it's not that I won't take the advice
> for using ElementTree, I just currently don't know anything about it.
> I just didn't want to say, "I have no idea what you're talking about!"
> to Scott cause I figured that would be rude, but I guess so is not
> saying anything, sorry. So I'll need to read up on it before I
> actually try to do anything with that approach.
> 
> Seeing the errors - I changed the two classes to this:
>   ... [some code that actually says a _little_ bit about his target] ....

If you had done a better job of asking your question, you'd have found a
quick answer.  That is why everyone points people at smartquestions, not
to pick on them.

Presuming you have an xml structure like:
     txt = '''<abc> something <def>
            <name name='steve' characterID='sid'> Some contents. </name>
            <name name='stevey' characterID='sidy'>Other contents.</name>
            </def></abc>'''
     import xml.etree.ElementTree as ET
     structure = ET.fromstring(xmls)
     for node in structure.findall('def/name'):
         print '%s: %s / %s: %s' % (node.tag, node.attrib['name'],
                               node.attrib['characterID'], node.text)

or a file named 'my.xml' with the same contents:
     import xml.etree.ElementTree as ET
     structure = ET.parse('my.xml')
     for node in structure.findall('def/name'):
         print '%s: %s / %s: %s' % (node.tag, node.attrib['name'],
                               node.attrib['characterID'], node.text)


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list