1

I'm trying the following XPath:

//*[local-name()='SN102'][1]

Using XPathTester, I saved my scenario http://www.xpathtester.com/xpath/94ee37e08960247a7bf0619d38c52bee

Not every HL1Loop has a SN102.
Otherwise, I could this:

//*[local-name()='HLLoop1'][1]//*[local-name()='SN102']

I have simplified the sample data down to the following:

<ns0:X12_00401_856 xmlns:ns0="http://schemas.microsoft.com/BizTalk/EDI/X12/2006">
  <ns0:HLLoop1>
   <ns0:SN1>
      <SN102>1</SN102>
      <SN103>EA</SN103>
      <SN108>AC</SN108>
    </ns0:SN1>
  </ns0:HLLoop1>
  <ns0:HLLoop1>
    <ns0:SN1>
      <SN102>2</SN102>
      <SN103>EA</SN103>
      <SN108>AC</SN108>
    </ns0:SN1>
  </ns0:HLLoop1>
</ns0:X12_00401_856>

The result is coming back with all nodes, not just the first one:

<?xml version="1.0" encoding="UTF-8"?>
<result>
<SN102>1</SN102>
<SN102>2</SN102>
</result>

How do I select the first node only. Seems simply, and I'm sure I've done it before, but not working today.

I have a "Vendor Simulator" program that is building fake 856 data to send back, and I want to increase the first quantity only to force some error handling logic.

NealWalters
  • 17,197
  • 42
  • 141
  • 251
  • I'm quite sure your simplified document does not reflect the real situation. The behavior you describe can only occur when `HLLoop1` elements are the respective first such elements within separate parents. – Tomalak May 03 '19 at 20:03
  • This is a FAQ. The fact that `[]` has higher precedence than `//` in XPath misleads many. Without an overriding `()`, `//a[1]` selects all `a` elements that are the first child of its parent. See duplicate links for further details and discussions. – kjhughes May 03 '19 at 20:05
  • Actually, the correct answer is in a note within the XPath specification itself: https://www.w3.org/TR/1999/REC-xpath-19991116/#path-abbrev – michael.hor257k May 03 '19 at 20:06
  • @michael.hor257k: Lots of good examples in the original, simple XPath spec, agreed. – kjhughes May 03 '19 at 20:08

1 Answers1

4

Just select the first element of the whole nodelist

(//*[local-name()='SN102'])[1]

The original query //*[local-name()='SN102'][1] would have selected the first SN102 if there had been several siblings of the same name.

choroba
  • 231,213
  • 25
  • 204
  • 289