xpath获取值和属性键

时间:2017-03-01 20:31:00

标签: xml postgresql xpath

美好的一天!任何人都可以帮助解析xml中attrbute的值和键,如:

使用

SELECT xpath('/el:GRID/@*',
'<el:GRID xmlns:el="http://example.com" xmlns:p="http://example1.com" p:title="Joda" p_titler="Dookoo">
    217
    <p:columns>
        <el:GRDCOL p:length="1">226
          <el:BOX p:kory="dory">228
          </el:BOX>
        </el:GRDCOL>
    </p:columns>
</el:GRID>',
  ARRAY[ARRAY['el', 'http://example.com'],array['p','http://example1.com']]);

我得到{Joda,Dookoo}

但我希望得到如下结果:

{p:title Joda, p_titler Dookoo}

我需要它来解析动态创建的xml,我不知道所有的属性名称......

1 个答案:

答案 0 :(得分:0)

如何获取XML属性的名称/值对:

with t(x,ns) as (values(
'<el:GRID xmlns:el="http://example.com" xmlns:p="http://example1.com" p:title="Joda" p_titler="Dookoo">
    217
    <p:columns>
        <el:GRDCOL p:length="1">226
          <el:BOX p:kory="dory">228
          </el:BOX>
        </el:GRDCOL>
    </p:columns>
</el:GRID>'::xml, ARRAY[ARRAY['el', 'http://example.com'],array['p','http://example1.com']]))

select tn.*, tv.*
  from t cross join lateral 
    (select * from unnest(xpath('/el:GRID/@*', t.x, t.ns)) with ordinality) as tv(v,i) cross join lateral
      (select * from unnest(xpath('name(/el:GRID/@*['||tv.i||'])', x, t.ns))) as tn(v)

要获得所需的效果,只需将select tn.*, tv.* from ...更改为select concat('{', string_agg(concat(tn.v, ' ', tv.v), ', '), '}') from ...

即可