I've got xml that looks like this:
<items>
<item>
<itemproperty>true</itemproperty>
<details>
<details>
<ID Type="z" Value="1"/>
<ID Type="w" Value="2"/>
</details>
</Locations>
</item>
<item>
<itemproperty>true</itemproperty>
<details>
<details>
<ID Type="a" Value="3"/>
<ID Type="b" Value="4"/>
</details>
</Locations>
</item>
</items>
I want to produce output like this:
ItemIndex DetailIDType DetailIDValue
1 z 1
1 w 2
2 a 3
2 b 4
I'm querying from the /items/item/details/detail/ID node and experimenting with trying to figure out the position/index of the ancestor item element. I can get the total count of item elements, but am struggling to find the position of the item element. In all cases it is not returning the correct index/position value:
SELECT DISTINCT
[TestGetItemElementName] = IDs.id.value('fn:local-name(./../../..)', 'varchar(50)')
,[TestGetItemElementCount] = IDs.id.value('count(/items/item)', 'int')
,[ItemIndexTest1] = IDs.id.value('for $i in ./../../.. return count(/items/item/*[. << $i]) + 1', 'int')
,[ItemIndexTest2] = IDs.id.value('for $i in . return count(../*[. << $i]) + 1', 'int')
,[DetailIDType] = convert(VARCHAR(256), IDs.id.query('data(./@Type)'))
,[DetailIDValue] = convert(VARCHAR(256), IDs.id.query('data(./@Value)'))
FROM
@x.nodes('/Recipients/Recipient/Locations/Location/ID') AS IDs(id)