1

I have a XML file stored in postgresql table which contains array attribute type contains values such as

<Type>
      <V Idx="1">Cat</V>
      <V Idx="2">Mouse</V>
      <V Idx="3">Tree</V>
   </Type>

and I would like to extract the Idx value of "Cat" using postgresql query.

1

1 Answer 1

0

You can use xpath() to use an XPath expression extracting parts of XML. It'll return an array of the matches, so you need to select the desired index if you want a scalar.

To get the Idx attribute of the first /Type/V that has a text of Cat you could use:

SELECT (xpath('(/Type/V[text()="Cat"]/@Idx)[1]', nmuloc))[1] idx
       FROM elbat;

db<>fiddle

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

2 Comments

It is working in but if xml header comes with url's it is not working. Can you please help me in that. For example : <sample-test-data-history xmlns="dmotorworks.com/sample-test-data-history"> <payPaymentCode> <V Idx="1">CASH</V> </payPaymentCode> <StatusCode>C98</StatusCode> <Type> <V Idx="1">Cat</V> <V Idx="2">Mouse</V> <V Idx="3">Tree</V> </Type> <totMiscCost> <V Idx="1">100.00</V> <V Idx="2">150.00</V> <V Idx="3">200.00</V> </totMiscCost> </sample-test-data-history>
From this xml i need to get the idx value of the array for which the text is "cat" and based on that Idx value I need to get totMiscCost from the next array attribute with the same Idx value

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.