需要通过在Oracle DB中查询来解析xmltype值

huangapple go评论68阅读模式
英文:

Need to parse xmltype values by querying it in Oracle DB

问题

我们需要使用选择语句从xmltype列中捕获值。以下是列"Test"中的值。

<c18>A</c18><c18 m="2">B</c18><c18 m="3">C</c18><c18 m="4"D</c18><c18 m="5">E</c18><c18 m="6">F</c18><c18 m="7">G</c18><c18 m="8">H</c18>

我们需要有8个新列,它们应该命名为"C1"、"C2"等,具有值A、B、C等等。

英文:

We have a requirement to capture the values from xmltype column using select statement. Below is the value we have in the column "Test".

<c18>A</c18><c18 m="2">B</c18><c18 m="3">C</c18><c18 m="4"D</c18><c18 m="5">E</c18><c18 m="6">F</c18><c18 m="7">G</c18><c18 m="8">H</c18>

We need to have 8 new columns which should be named as "C1", "C2", etc having values A,B,C and so on.

答案1

得分: 1

您的XML无效(在m="4"之后缺少闭合>,并且没有根元素)。如果您修复了这个问题,然后您可以使用:

SELECT x.*
FROM   table_name t
       CROSS APPLY XMLTABLE(
         '/root'
         PASSING t.test
         COLUMNS
           c1 VARCHAR2(20) PATH './c18[not(@m)]',
           c2 VARCHAR2(20) PATH './c18[@m="2"]',
           c3 VARCHAR2(20) PATH './c18[@m="3"]',
           c4 VARCHAR2(20) PATH './c18[@m="4"]',
           c5 VARCHAR2(20) PATH './c18[@m="5"]',
           c6 VARCHAR2(20) PATH './c18[@m="6"]',
           c7 VARCHAR2(20) PATH './c18[@m="7"]',
           c8 VARCHAR2(20) PATH './c18[@m="8"]'
       ) x

对于示例数据:

CREATE TABLE table_name (test XMLTYPE);

INSERT INTO table_name (test)
VALUES (XMLTYPE( '<root><c18>A</c18><c18 m="2">B</c18><c18 m="3">C</c18><c18 m="4">D</c18><c18 m="5">E</c18><c18 m="6">F</c18><c18 m="7">G</c18><c18 m="8">H</c18></root>' ) );

输出:

C1 C2 C3 C4 C5 C6 C7 C8
A B C D E F G H

fiddle

英文:

Your XML is invalid (it is missing a closing > after m="4" and does not have a root element). If you fix that then you can use:

SELECT x.*
FROM   table_name t
       CROSS APPLY XMLTABLE(
         '/root'
         PASSING t.test
         COLUMNS
           c1 VARCHAR2(20) PATH './c18[not(@m)]',
           c2 VARCHAR2(20) PATH './c18[@m="2"]',
           c3 VARCHAR2(20) PATH './c18[@m="3"]',
           c4 VARCHAR2(20) PATH './c18[@m="4"]',
           c5 VARCHAR2(20) PATH './c18[@m="5"]',
           c6 VARCHAR2(20) PATH './c18[@m="6"]',
           c7 VARCHAR2(20) PATH './c18[@m="7"]',
           c8 VARCHAR2(20) PATH './c18[@m="8"]'
       ) x

Which, for the sample data:

CREATE TABLE table_name (test XMLTYPE);

INSERT INTO table_name (test)
VALUES (XMLTYPE( '<root><c18>A</c18><c18 m="2">B</c18><c18 m="3">C</c18><c18 m="4">D</c18><c18 m="5">E</c18><c18 m="6">F</c18><c18 m="7">G</c18><c18 m="8">H</c18></root>' ) );

Outputs:

C1 C2 C3 C4 C5 C6 C7 C8
A B C D E F G H

fiddle

huangapple
  • 本文由 发表于 2023年6月6日 16:24:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定