Reputation: 1513
Suppose I have an XML file as following:
my_data.xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<country name="Liechtenstein" xmlns="aaa:bbb:ccc:liechtenstein:eee">
<rank updated="yes">2</rank>
<holidays>
<christmas>Yes</christmas>
</holidays>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore" xmlns="aaa:bbb:ccc:singapore:eee">
<continent>Asia</continent>
<holidays>
<christmas>Yes</christmas>
</holidays>
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama" xmlns="aaa:bbb:ccc:panama:eee">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
<ethnicity xmlns="aaa:bbb:ccc:ethnicity:eee">
<malay>
<holidays>
<ramadan>Yes</ramadan>
</holidays>
</malay>
</ethnicity>
</data>
After parsing:
xtree = etree.parse('my_data.xml')
xroot = xtree.getroot()
I want to search for elements with tag holidays
, but only under the path of ethnicity
.
This line:
holiday_nodes = xroot.xpath('.//*[local-name()="holidays"]')
will give me all holiday nodes, like this:
[<Element {aaa:bbb:ccc:liechtenstein:eee}holidays at 0x19013f926c0>,
<Element {aaa:bbb:ccc:singapore:eee}holidays at 0x19013f92880>,
<Element {aaa:bbb:ccc:ethnicity:eee}holidays at 0x19012cdc0c0>]
What is the syntax to achieve this search? Thanks.
Upvotes: 1
Views: 349
Reputation: 4844
Use
.//*[local-name()="ethnicity"]//*[local-name()="holidays"]
And if malay
is always the element in between use for better performance
.//*[local-name()="ethnicity"]/*[local-name()="malay"]/*[local-name()="holidays"]
Upvotes: 1
Reputation: 52858
Try the following xpath...
.//*[local-name()="ethnicity"]//*[local-name()="holidays"]
Upvotes: 1