Oracle XMLTYPE 提取第一个节点

Oracle XMLTYPE extract first node

我在从 Oracle XML 的特定元素中提取第一个节点时遇到问题。

这是XML:

<data type="TestData" version="1">
  <MasterTable Name="TestMaster"/>
  <Table Name="TestTable1">Test</Table>
  <Table Name="TestTable2"/>
  <Table Name="TestTable3"/>
  <Table Name="TestTable4"/>
  <Table Name="TestTable5"/>
  <Table Name="TestTable6"/>
  <Table Name="TestTable7"/>
  <Table Name="TestTable8"/>
  <Table Name="TestTable9"/>
  <Table Name="TestTable10"/>
  <Table Name="TestTable11"/>
  <Table Name="TestTable12"/>
  <Table Name="TestTable13"/>
  <Table Name="TestTable14"/>
  <Fact Name="TestFact1"/>
</data>

我正在尝试提取第一个名称元素 "TestTable1" 的值和第一个名称元素 "Test" 的文本。

我有以下查询只返回空值:

select a.xml.extract('//Name[1]') from my_table a; --Attempting to return "TestTable1" from Name attribute 1



select a.xml.extract('//Name[1]/text()') from my_table a; --Attempting to return the text "Test" from Name attribute 1
with test as( select xmltype('<data type="TestData" version="1">
  <MasterTable Name="TestMaster"/>
  <Table OtherName="TestTable1">OtherTable</Table>
  <Table Name="TestTable1">Test</Table>
  <Table Name="TestTable2"/>
  <Table Name="TestTable3"/>
  <Table Name="TestTable4"/>
  <Table Name="TestTable5"/>
  <Table Name="TestTable6"/>
  <Table Name="TestTable7"/>
  <Table Name="TestTable8"/>
  <Table Name="TestTable9"/>
  <Table Name="TestTable10"/>
  <Table Name="TestTable11"/>
  <Table Name="TestTable12"/>
  <Table Name="TestTable13"/>
  <Table Name="TestTable14"/>
  <Fact Name="TestFact1"/>
</data>') x from dual)


select t.x.extract('//Table[@Name][1]'),t.x.extract('//Table[1]'),  t.x.extract('//Table[@Name][1]/text()'),t.x.extract('//Table[1]/text()'),t.x.extract('//Table[./text()][1]') from test t;

t.x.extract('//Table[@Name][1]') return先'Table';具有属性名称 t.x.extract('//Table[1]') return 先 'Table';
t.x.extract('//Table[./text()][1]') return 第一个非空 table 元素;

您可以使用 XMLTABLE:

SQL Fiddle

Oracle 11g R2 架构设置:

CREATE TABLE table_name ( xml ) as
select xmltype('<data type="TestData" version="1">
  <MasterTable Name="TestMaster"/>
  <Table OtherName="TestTable1">OtherTable</Table>
  <Table Name="TestTable1">Test</Table>
  <Table Name="TestTable2"/>
  <Table Name="TestTable3"/>
  <Table Name="TestTable4"/>
  <Table Name="TestTable5"/>
  <Table Name="TestTable6"/>
  <Table Name="TestTable7"/>
  <Table Name="TestTable8"/>
  <Table Name="TestTable9"/>
  <Table Name="TestTable10"/>
  <Table Name="TestTable11"/>
  <Table Name="TestTable12"/>
  <Table Name="TestTable13"/>
  <Table Name="TestTable14"/>
  <Fact Name="TestFact1"/>
</data>') from dual;

查询 1:

SELECT x.*
FROM   table_name t
       CROSS JOIN
       XMLTABLE(
         '/data/Table[@Name][1]'
         PASSING t.xml
         COLUMNS Name VARCHAR2(20) PATH '@Name'
       ) x

Results:

|       NAME |
|------------|
| TestTable1 |