AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 341427
Accepted
Gareth Vaughan
Gareth Vaughan
Asked: 2024-08-05 18:29:19 +0800 CST2024-08-05 18:29:19 +0800 CST 2024-08-05 18:29:19 +0800 CST

Como extrair atributos indeterminados do xml em um banco de dados postgres?

  • 772

Herdei um banco de dados legado no qual os dados do Excel são armazenados em uma coluna de texto de uma tabela em um banco de dados postgres. Um valor dessa coluna pode ser semelhante a:

<Sheets>
  <Sheet1>
    <Addresses E54="3" G23="1.1" N87="0"/>
  </Sheet1>
  <Sheet2>
    <Addresses W32="thing"/>
  </Sheet2>
</Sheets>

Eu sei que posso escolher valores de endereços específicos com

select  xpath( '//Addresses/@E54',  cast(ssd.data as xml)) from spreadsheetdata ssd 

mas não tenho ideia de quantos endereços distintos existem.

O que espero fazer é produzir uma tabela parecida com:

sheet       address      value
Sheet1      E54          "3"
Sheet1      G23          "1.1"
Sheet1      N87          "0"
Sheet2      W32          "thing"
...

Como faço isso?

postgresql
  • 1 1 respostas
  • 20 Views

1 respostas

  • Voted
  1. Best Answer
    Gareth Vaughan
    2024-08-08T07:11:16+08:002024-08-08T07:11:16+08:00

    Minha solução foi primeiro converter o xml para json; xml_to_json

    Então eu defini:

    -- converts xml from data in spreadsheet templates table into a table via json
    CREATE OR REPLACE FUNCTION public.xml_to_table(xml)
        RETURNS TABLE(sheetname text, attributename text, attributevalue text) 
        LANGUAGE 'sql'
        COST 100
        VOLATILE PARALLEL UNSAFE
        ROWS 1000
    
    AS $BODY$
         -- from the records returned by the subquery below this returns records with columns SheetName, 
        -- attribute name (address) and attribute value e.g.:
        -- Sheet1   E54   3
        -- Sheet1   G23   1.1
        -- Sheet1   N87   0
        -- Sheet2   W32   thing
        -- ... 
        
        select      
            e.sheetname, 
            jsonb_object_keys(e.attr) as attributename, 
            e.attr ->> jsonb_object_keys(e.attr) as attributevalue
        from 
        (
            -- removes the rows with null for the list of attributes from the results from the subquery under this, and 
            -- separates each attribute to its own row e.g.:
            -- Sheet1   {"E54": "3"}
            -- Sheet1   {"G23": "1.1"}
            -- Sheet1   {"N87": "0"}
            -- Sheet2   {"W32": "thing"}
            -- ... 
            select 
                d.sheetname, 
                jsonb_array_elements(d.exceldata) as attr
            from 
            (
                -- separates each line from the subquery under this into records containging columns for sheetname, and 
                -- this can handle xml having more than one element at the addresses level 
                -- (e.g. it can handle a NamedeCells element alongside Addresses )
                -- Sheet1       [{"E54": "3"},  ...
                -- Sheet2       [{"W32": "thing"}]
                -- ...
                select 
                    b.sheetname, 
                    b.records -> jsonb_object_keys(b.records) -> 'attr' as exceldata
                from 
                (
                    -- separates each line from the subquery under this into records with columns for sheetname and 
                    -- a row for the JSON for each of Addresses e.g.:
                    -- Sheet1    {Addresses: {attr: ...
                    -- Sheet2    {Addresses: {attr: ...
                    --  ...
                    select 
                        jsonb_object_keys(a.sheetjson) as sheetname,  
                        jsonb_array_elements((a.sheetjson->jsonb_object_keys(a.sheetjson) -> 'childs')) as records
                    from 
                    (
                        -- separates the supplied xml into json records for each sheet e.g.:
                        -- {Sheet1: {attr: ...
                        -- {Sheet2: {attr: ...
                        -- ...
                        select 
                            jsonb_array_elements(xml_to_json($1)->'Sheets'->'childs')  as sheetjson
                    ) as a
                ) as b
            ) as d
        ) as e;
    
    $BODY$;
    

    isso pode ser chamado com

    select * from xml_to_table('<Sheets>
      <Sheet1>
        <Addresses E54="3" G23="1.1" N87="0"/>
      </Sheet1>
      <Sheet2>
        <Addresses W32="thing"/>
      </Sheet2>
    </Sheets>')
    

    para produzir

    nome da planilha Nome do Atributo Valor do atributo
    Folha1 E54 3
    Folha1 G23 1.1
    Folha1 N87 0
    Planilha2 W32 coisa

    Esta função não é geral como eu gostaria, mas será suficiente para minhas necessidades de limpeza de dados

    Quaisquer comentários são bem-vindos.

    • 2

relate perguntas

  • Posso ativar o PITR depois que o banco de dados foi usado

  • Práticas recomendadas para executar a replicação atrasada do deslocamento de tempo

  • Os procedimentos armazenados impedem a injeção de SQL?

  • Sequências Biológicas do UniProt no PostgreSQL

  • Qual é a diferença entre a replicação do PostgreSQL 9.0 e o Slony-I?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve