XPath节点解析需求:按索引获取双条件匹配的ItemKey值
The issue with your current XPath is that it first selects all Ref nodes with Location="C1"—including those whose parent Level2 node doesn't have an EventData ID="W12"—and then uses that index to pick a node. This means your index includes irrelevant entries (like the first C1 Ref that lacks the W12 EventData).
Instead, you need to first filter the Level2 nodes to only those that satisfy both conditions: having a Ref[@Location='C1'] and an EventData[@ID='W12']. Then you can index into this pre-filtered set to get the exact ItemKey you want.
Solution XPath (XPath 1.0 Compatible)
Use this expression, replacing N with 1, 2, or 3 to match your desired index:
(/Object/Level1/Level2[Ref[@Location='C1'] and EventData[@ID='W12']])[N]/EventData[@ID='W12']/FormData/ItemData/@ItemKey
Breakdown:
Level2[Ref[@Location='C1'] and EventData[@ID='W12']]: This filters theLevel2nodes to only those that contain both the requiredRefandEventDataelements. This gives you exactly the 3 nodes you care about.(...) [N]: Indexes into this filtered set—[1]for the first matching node,[2]for the second, etc.- The rest of the path navigates to the
ItemKeyattribute within that node'sEventDatasection.
Example Results:
- For index 1:
(/Object/Level1/Level2[Ref[@Location='C1'] and EventData[@ID='W12']])[1]/EventData[@ID='W12']/FormData/ItemData/@ItemKey→ ReturnsItemKey="1" - For index 2: Replace
[1]with[2]→ ReturnsItemKey="2" - For index 3: Replace
[1]with[3]→ ReturnsItemKey="3"
This approach ensures your index only applies to nodes that meet both of your criteria, exactly matching the behavior you're looking for.
内容的提问来源于stack exchange,提问作者user2568374

