The trouble with "dynamic attributes".
Lie Ryan
lie.1296 at gmail.com
Sun Sep 19 02:47:26 EDT 2010
On 09/18/10 03:53, Ethan Furman wrote:
> Lie Ryan wrote:
> [snip]
>> And even dict-syntax is not perfect for accessing XML file, e.g.:
>>
>> <a>
>> <b>foo</b>
>> <b>bar</b>
>> </a>
>>
>> should a['b'] be 'foo' or 'bar'?
>
> Attribute style access would also fail in this instance -- how is this
> worked-around?
By not having multiple b in the first place!
However, if you cannot avoid having duplicates, then you would have to
use a different approach:
SAX (Simple API for XML; Java has a weird sense of simplicity):
import xml.sax as sax
from xml.sax.handler import ContentHandler
class MyHandler(ContentHandler):
def __init__(self):
self.inB = False
def startElement(self, name, attrs):
if name == 'b':
self.inB = True
def characters(self, ch):
if self.inB:
print ch
def endElement(self, name):
if name == 'b':
self.inB = False
data = '<a><b>Foo</b><c>Evil</c><b>Bar</b></a>'
sax.parseString(data, MyHandler())
or in ElementTree:
import xml.etree.ElementTree as et
data = '<a><b>Foo</b><c>Evil</c><b>Bar</b></a>'
a = et.fromstring(data)
for elem in a.findall('b'):
print elem.text
More information about the Python-list
mailing list