Vojtech
Vojtech

Reputation: 2603

How to select node that contains a certain substring in child nodes?

I have an XML of similar structure containing many items:

<Items>
  <Item>
    <Name>Item name 1</Name>
    <Details>
      <Detail>ABC DEF</Detail>
      <Detail>GHI JKL</Detail>
    </Details>
  </Item>
  <Item>
    <Name>Item name 2</Name>
    <Details>
      <Detail>ABC DEF</Detail>
      <Detail>GHI MNO</Detail>
    </Details>
  </Item>
</Items>

How can I get a list of all Item nodes that contain substring "MNO" in at least one of their Detail subnode?

This expression does not return expected Item with Description "Item name 2":

/Items/Item[contains(Details/Detail, 'MNO')]

Please advise. Many thanks in advance! Vojtech

Upvotes: 1

Views: 1159

Answers (1)

Alexander Yezutov
Alexander Yezutov

Reputation: 3214

Here is the working variant:

/Items/Item[Details/Detail[contains(.,"MNO")]]

Basically, what happened in your example: The "MNO" string was searched for containment only in first Detail node. So, if you would change XML to:

<Items>
  <Item>
    <Name>Item name 1</Name>
    <Details>
      <Detail>ABC DEF</Detail>
      <Detail>GHI JKL</Detail>
    </Details>
  </Item>
  <Item>
    <Name>Item name 2</Name>
    <Details>
      <!-- Nodes order was changed -->
      <Detail>GHI MNO</Detail>
      <Detail>ABC DEF</Detail>
    </Details>
  </Item>
</Items>

your XPath would work fine.

Upvotes: 4

Related Questions