I need to extract three columns of data from an xml column in postgres, such that the xml is expanded into it's appropriate columns. One of these columns needs to be an attribute of one nesting level of the xml, and the other columns are attributes of the nest one level down. The data from the higher level should be repeated. Is this possible? See the example below for something concrete.
Thanks, --sw
Consider the below query:
with x as (select
'<catalog catalog-id="manufacturer-catalog-id">
<category-assignment category-id="category1" product-id="product1"/>
<category-assignment category-id="category1" product-id="product2"/>
<category-assignment category-id="category2" product-id="product3"/>
</catalog>'::xml as t
)
(
select
xpath('/catalog/@catalog-id', catalog_xml) catalog_id,
xpath('//@category-id', catalog_xml) category_assignment_category_id,
xpath('//@product-id', catalog_xml) category_assignment_product_id
from (select unnest(xpath('/catalog', t)) catalog_xml from x) q
)
This query returns this data:
"{manufacturer-catalog-id}";"{category1,category1,category2}";"{product1,product2,product3}"
This query:
with x as (select
'<catalog catalog-id="manufacturer-catalog-id">
<category-assignment category-id="category1" product-id="product1"/>
<category-assignment category-id="category1" product-id="product2"/>
<category-assignment category-id="category2" product-id="product3"/>
</catalog>'::xml as t
)
(
select
xpath('/catalog/@catalog-id', catalog_xml) catalog_id,
xpath('//@category-id', catalog_xml) category_assignment_category_id,
xpath('//@product-id', catalog_xml) category_assignment_product_id
from (select unnest(xpath('/catalog/category-assignment', t)) catalog_xml from x) q
)
---EDITED---
returns this data:
"{}";"{category1}";"{product1}"
"{}";"{category1}";"{product2}"
"{}";"{category2}";"{product3}"
I need this data:
"{manufacturer-catalog-id}";"{category1}";"{product1}"
"{manufacturer-catalog-id}";"{category1}";"{product2}"
"{manufacturer-catalog-id}";"{category2}";"{product3}"