User1
User1

Reputation: 41241

OPENXML in Postgres

SQLServer has a very useful function called OPENXML. It works is used like this:

DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
   <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
      <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
      <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
   </Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
   <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
      <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

-- Execute a SELECT statement that uses the OPENXML rowset provider.
SELECT *
FROM OPENXML (@idoc, '/ROOT/Customer',1)
WITH (CustomerID  varchar(10),
      ContactName varchar(20))

With a result:

CustomerID ContactName          
---------- -------------------- 
VINET      Paul Henriot
LILAS      Carlos Gonzlez

Does someone know of an alternative for Postgres?

Upvotes: 2

Views: 1590

Answers (2)

Billy
Billy

Reputation: 2436

I'm sure this code can be improved, but this appears to return the same result in Postgres as the code you posted does in SQL Server.

WITH test_xml(data) AS (VALUES
  ('<ROOT>
    <Customer CustomerID="VINET" ContactName="Paul Henriot">
       <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
          <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
          <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
       </Order>
    </Customer>
    <Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
       <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
          <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
       </Order>
    </Customer>
    </ROOT>'::XML)
)
SELECT  unnest((xpath('//Customer/@CustomerID', test_xml.data))),
        unnest((xpath('//Customer/@ContactName', test_xml.data)))
FROM test_xml

Upvotes: 1

Peter Eisentraut
Peter Eisentraut

Reputation: 36749

This is currently not possible in PostgreSQL (unless someone has written awesome code that he didn't tell anyone about until now).

Upvotes: 1

Related Questions