简体   繁体   中英

Select a specific child node based on tag using XPath or lxml

I have an XML file similar to this. And I'd like to select a child node based on its tag

<list>
  <age>
    <John>18</John>
    <Tom>22</Tom>
    <Samer>19</Samer>
    <Mark>21</Mark>
  </age>
</list>

Is there a way to select "Tom node" for example, starting from the "age node"?

I tried something like that ageNode.xpath("/Tom") but it's not working. The ageNode.getchildren()[1] works, but the thing is order is different every time. So I can only depend on tag NOT on order .

I'm using python 2.7 and lxml package.

/ at the beginning of XPath always reference the root node. To do a relative XPath, you need to either add a . or remove / completely, as mentioned in the comment :

ageNode.xpath("./Tom")
ageNode.xpath("Tom")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM