0

What is the XPath syntax that returns multiple nodes from XML?

Say I have XML like so:

<Contacts>
  <Contact>
    <Name>
      <FirstName>Andre</FirstName>
      <LastName>Levy</LastName>
    </Name>
    <DOB>
      <Year>1970</Year>
      <Month>5</Month>
      <Day>13</Day>
    </DOB>
  </Contact>
  <Contact>
    <Name>
      <FirstName>Bob</FirstName>
      <LastName>Fisher</LastName>
    </Name>
    <DOB>
      <Year>1983</Year>
      <Month>7</Month>
      <Day>24</Day>
    </DOB>
  </Contact>
</Contacts>

What XPath will give me:

<Contacts>
  <Contact>
    <FirstName>Andre</FirstName>
    <Year>1970</Year>
  </Contact>
  <Contact>
    <FirstName>Bob</FirstName>
    <Year>1983</Year>
  </Contact>
</Contacts>

I tried: //FirstName | //Year

But that only yields:

<FirstName>Andre</FirstName>
<FirstName>Bob</FirstName>
<Year>1970</Year>
<Year>1983</Year>

What gives?

2

1 Answer 1

3

You can select multiple nodes in XPath, but you cannot re-arrange XML in the manner exhibited in your requested output.

Also note:

  1. Your sample XML is not well-formed; it must have a single root element.
  2. You can indeed select multiple nodes as your title question asks using the union operator | you suggest, however...
  3. Your desired XML is not available for selection, which XPath does, but it could be constructed via transformation, which XSLT does (provided you're willing to wrap the desired XML in a single enclosing root element).
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I've added the single root element. Is that what you meant?
Yes, that covers #1, but that's the easy part; understand that #3 is the hard part. You need to use XSLT or another language hosting XPath when you want to rearrange that which you select via XPath.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.