如何从Oracle SQL Developer中提取XML数据

时间:2019-01-23 06:18:52

标签: sql xml oracle

我正在尝试从包含消息列的反馈表中提取XML数据;下面是XML代码:

<?xml version="1.0" encoding="UTF-8"?>
<message>Hi Hello</message>
<channel>XYZ</channel>
<sentiment-score>5.0</sentiment-score>
<structured-fields>
<structured-filed><name>NA_score</name><value>5</value></structured-filed>
<structured-filed><name>NPS_score</name><value>10</value></structured-filed>
<structured-fields>

我需要从消息列中提取上述XML代码。

1 个答案:

答案 0 :(得分:0)

您的XML文档需要有一个single XML element as the document root

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <message>Hi Hello</message>
  <channel>XYZ</channel>
  <sentiment-score>5.0</sentiment-score>
  <structured-fields>
    <structured-field><name>NA_score</name><value>5</value></structured-field>
    <structured-field><name>NPS_score</name><value>10</value></structured-field>
  </structured-fields>
</root>

确定后,只需使用XMLTable和XPath:

SELECT *
FROM   XMLTABLE(
         '/root'
         PASSING XMLType( '<?xml version="1.0" encoding="UTF-8"?><root><message>Hi Hello</message><channel>XYZ</channel><sentiment-score>5.0</sentiment-score><structured-fields><structured-field><name>NA_score</name><value>5</value></structured-field><structured-field><name>NPS_score</name><value>10</value></structured-field></structured-fields></root>' )
         COLUMNS
         MESSAGE         VARCHAR2(200) PATH '//message',
         CHANNEL         VARCHAR2(200) PATH '//channel',
         SENTIMENT_SCORE NUMBER(3,1)   PATH '//sentiment-score',
         NA_SCORE        NUMBER(3,0)   PATH '//structured-fields/structured-field[name/text()="NA_score"]/value',
         NPS_SCORE       NUMBER(3,0)   PATH '//structured-fields/structured-field[name/text()="NPS_score"]/value'
       );

输出

MESSAGE  | CHANNEL | SENTIMENT_SCORE | NA_SCORE | NPS_SCORE
:------- | :------ | --------------: | -------: | --------:
Hi Hello | XYZ     |               5 |        5 |        10

db <>提琴here