arrays - How to use xpath in Postgres to align XML elements -
this query:
with x (select '<promotions> <promotion promotion-id="old-promotion"> <enabled-flag>true</enabled-flag> <searchable-flag>false</searchable-flag> </promotion> <promotion promotion-id="new-promotion"> <enabled-flag>false</enabled-flag> <searchable-flag>false</searchable-flag> <exclusivity>no</exclusivity> <price>100</price> <price>200</price> <price>300</price> </promotion> </promotions>'::xml t ) select xpath('/promotions/promotion/@promotion-id', t) promotion_id, xpath('/promotions/promotion/enabled-flag/text()', t) enabled_flag, xpath('/promotions/promotion/exclusivity/text()', t) exclusivity, xpath('/promotions/promotion/price/text()', t) price x
for elements exclusivity
, price
not appear in first promotion, appear in second, yields result:
"{old-promotion,new-promotion}";"{true,false}";"{no}";"{100,200,300}"
i need figure out how can result set allow me line exclusivity , price data appropriate promotion_id's. this
"{old-promotion,new-promotion}";"{true,false}";"{,no}";"{,"100,200,300"}"
what have make happen?
consider this:
with x (select '<promotions> <promotion promotion-id="old-promotion"> <enabled-flag>true</enabled-flag> <searchable-flag>false</searchable-flag> </promotion> <promotion promotion-id="new-promotion"> <enabled-flag>false</enabled-flag> <searchable-flag>false</searchable-flag> <exclusivity>no</exclusivity> <price>100</price> <price>200</price> <price>300</price> </promotion> </promotions>'::xml t ) select xpath('//@promotion-id', node) promotion_id ,xpath('//enabled-flag/text()', node) enabled_flag ,xpath('//exclusivity/text()', node) exclusivity ,xpath('//price/text()', node) price (select unnest(xpath('/promotions/promotion', t)) node x) sub
the trick split document nodes first of unnest()
.
extract attributes each node. way null
values automatically missing attributes.
returns:
promotion_id | enabled_flag | exclusivity | price -----------------+--------------+-------------+--------------- {old-promotion} | {true} | {} | {} {new-promotion} | {false} | {no} | {100,200,300}
related question:
xpath query hierarchical data, preserving ancestor–descendant relationship
Comments
Post a Comment