1

I have the following XML and you can see it contains three LevelA elements. I want to fetch /LevelA/Value (which is 9101) where /LevelA/LevelB2/LevelC == "Address". Now in PROD, the position of elements might change and so the address element might be first or last or in the middle. I am able to write two separate queries based on indexes but how to write one xpath query that contains the condition within it for matching with address and gives back 9101 independent of position of Level A elements.

DECLARE @x XML;
SET @x = '
<root>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Item4</LevelC>
            <LevelC2>Item5</LevelC2>
            <LevelC3>
                <anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">123456</anyType>
            </LevelC3>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:boolean">true</Value>
    </LevelA>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Item4</LevelC>
            <LevelC2>Item5</LevelC2>
            <LevelC3>
                <anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">123456</anyType>
            </LevelC3>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:boolean">true</Value>
    </LevelA>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Address</LevelC>
            <LevelC2>House</LevelC2>
            <LevelC3/>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">9101</Value>
    </LevelA>
</root>
'
SELECT @x.value('/root[1]/LevelA[3][1]/LevelB2[1]/LevelC[1]', 'varchar(max)')
SELECT @x.value('/root[1]/LevelA[3][1]/Value[1]', 'int')

enter image description here

1 Answer 1

1

You can do

SELECT @x.value('(/root/LevelA[LevelB2/LevelC = "Address"]/Value)[1]', 'int')

To apply the predicate to LevelA that LevelB2/LevelC/text() is "Address"

DB Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.