Home > Software design >  XPath 1.0, 1st node in subtree
XPath 1.0, 1st node in subtree

Time:12-24

So what I want to do is identify the 1st node in some subtree of a xml tree.

here's an example

<?xml version="1.0" encoding="utf-8"?>
<root>
  <road>
    <households>
      <household>
        <occupants>
          <person name="jim"/>
          <person name="jon"/>
          <person name="julie"/>
          <person name="janet"/>
        </occupants>
      </household>
      <household>
        <occupants>
          <person name="brenda"/>
          <person name="bert"/>
          <person name="billy"/>
        </occupants>
      </household>
    </households>
  </road>
  <road>
    <households>
      <household>
        <occupants>
        </occupants>
      </household>
      <household>
        <occupants>
          <person name="arthur"/>
          <person name="aimy"/>
        </occupants>
      </household>
      <household>
        <occupants>
          <person name="harry"/>
          <person name="henry"/>
        </occupants>
      </household>
    </households>
  </road>
</root>

now I want the 1st person mentioned per road.

so lets have a go...

/root/road/households/household/occupants/person[1]/@name

that returns the 1st person per occupants node.

lets try

(/root/road/households/household/occupants/person)[1]/@name

that returns the 1st person in the whole tree

what I sort of want to do is?

/root/road/(households/household/occupants/person)[1]/@name

i.e. take the 1st person in the set of people in a road

but thats not valid xpath 1.0

CodePudding user response:

This seems to be what you’re after, using the descendant axis:

/root/road/descendant::person[1]/@name
  • Related