查询 XML CLOB 列以获取列中的子 XML

Query XML CLOB column to get sub XML in the column

我的 table 中有一个 CLOB 列,其中包含一个 XML。我想在特定标签之后获取 xml 到其结束标签,即

CLOB 列中的完整 XML

<ParentTag>
 <Location>ABC XYZ ....</Location>
 <Person>
  <Name>Mohsin</Name>
  <Age>23</Age>
 </Person>
</ParentTag>

我要获取的是这样的:

<Person>
  <Name>Mohsin</Name>
  <Age>23</Age>
</Person>

我曾尝试使用 dbms_lob.substrdbms_lob.getlength 但这对子 XML 可能包含 <Person> 标记,在不同情况下以不同字节开始。

如有任何帮助,我们将不胜感激。 谢谢

不要尝试自己用子字符串解析节点。 Oracle 具有广泛的 XML support built-in. You can do this with an XMLQuery:

select xmlquery('/ParentTag/Person' passing xmltype(xml_clob) returning content)
  as xml_value
from your_table;

XML_VALUE                                                                      
--------------------------------------------------------------------------------
<Person><Name>Mohsin</Name><Age>23</Age></Person>

如果您的 XML 文档(在 CLOB 中)可以有多个人员节点,那么您可以使用 XMLTable 来提取它们。

如果您希望它是与您显示的内容相匹配的格式化字符串,而不是 XML 文档,您可以使用 XMLSerialize 包装器调用:

select xmlserialize(content
  xmlquery('/ParentTag/Person' passing xmltype(xml_clob) returning content)
    as varchar2(100) indent size=2) as string_value
from your_table;

STRING_VALUE                                                                   
--------------------------------------------------------------------------------
<Person>                                                                        
  <Name>Mohsin</Name>                                                           
  <Age>23</Age>                                                                 
</Person>

跟进评论,如果你有命名空间,你可以 declare that as part of the XPath:

select xmlquery('declare namespace NS4 = "http://soa.comptel.com/2011/02/instantlink"; /ParentTag/NS4:Person'
  passing xmltype(prov_request) returning content) as xml_value
from your_table;

select xmlserialize(content
  xmlquery('declare namespace NS4 = "http://soa.comptel.com/2011/02/instantlink"; /ParentTag/NS4:Person'
      passing xmltype(prov_request) returning content)
    as varchar2(150) indent size=2) as string_value
from your_table;

提取的 Person 节点仍将具有该命名空间信息:

STRING_VALUE                                                                   
--------------------------------------------------------------------------------
<NS4:Person xmlns:NS4="http://soa.comptel.com/2011/02/instantlink">             
  <NS4:Name>Mohsin</NS4:Name>                                                   
  <NS4:Age>23</NS4:Age>                                                         
</NS4:Person>