xml_select and namespaces

7 views
Skip to first unread message

Adam Olsen

unread,
Jul 19, 2009, 12:29:42 PM7/19/09
to akara
Given the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="urn:goonswarm:core:1" id="4514099">
<api-keys>
<api-key type="limited" href="http://localhost:1521/api/1/api-keys/
1/"/>
</api-keys>
</user>

How can I select the href attribute using xml_select?

doc.xml_select(u'user/api-keys/api-key/@href') selects nothing, I
believe it's because of the namespace

Uche Ogbuji

unread,
Jul 19, 2009, 1:12:17 PM7/19/09
to ak...@googlegroups.com
Yep.  It's is an XPath FAQ.

http://xml3k.org/Amara/FAQ#XPath.28e.g.xmlxpathmethod.29andXSLTpatternsdonotworkwithdefaultnamespaces.3F

That recipe I need to update that FAQ for Amara 2, but this should help:

XML = """<?xml version="1.0" encoding="UTF-8"?>

<user xmlns="urn:goonswarm:core:1" id="4514099">
       <api-keys>
               <api-key type="limited" href="http://localhost:1521/api/1/api-keys/
1/"/>
        </api-keys>
</user>"""

from amara.bindery import parse #Doesn't yet work for non-bindery parse.  We're thinking about this
doc = parse(XML, prefixes={'ns': 'urn:goonswarm:core:1'})
print doc.xml_select(u'ns:user/ns:api-keys/ns:api-key/@href')[0].xml_value

#For non-bindery parse:

from amara import parse
doc = parse(XML)
PREFIXES = {'ns': 'urn:goonswarm:core:1'}
print doc.xml_select(u'ns:user/ns:api-keys/ns:api-key/@href', prefixes=PREFIXES)[0].xml_value


--
Uche Ogbuji                       http://uche.ogbuji.net
Founding Partner, Zepheira        http://zepheira.com
Linked-in profile: http://www.linkedin.com/in/ucheogbuji
Articles: http://uche.ogbuji.net/tech/publications/
friendfeed: http://friendfeed.com/uche
Join me at STC09:
* http://www.semantic-conference.com
* http://friendfeed.com/stc09


Reply all
Reply to author
Forward
0 new messages