How to select multiple nodes from XML with XPath?

2020-03-31 07:30发布

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?

标签: xml xpath
1条回答
Fickle 薄情
2楼-- · 2020-03-31 08:05

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).
查看更多
登录 后发表回答