如何查找具有某些属性和嵌套元素的XML文档?

时间:2016-12-02 07:02:18

标签: sql xml oracle

我正在搜索可以在Oracle数据库中查找行的正则表达式。行包含一个如下所示的字符串:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<characteristics>
  <characteristic id="1001" mandatory="true" seq="1">
    <wildcard/>
  </characteristic>
  <characteristic id="10001" mandatory="false" seq="1">
    <value negation="false" seq="1">63</value>
  </characteristic>
  <characteristic id="10002" mandatory="false" seq="1">
    <value negation="false" seq="1">64</value>
  </characteristic>
  <characteristic id="10051" mandatory="false" seq="1">
    <value negation="false" seq="1">65</value>
  </characteristic>
  <characteristic id="10052" mandatory="false" seq="1">
    <value negation="false" seq="1">66</value>
  </characteristic>
  <characteristic id="1010" mandatory="false" seq="100">
    <wildcard/>
    <value negation="false" seq="1">314</value>
  </characteristic>
</characteristics>

正则表达式必须查找包含具有包含通配符的特殊ID的特征的所有行:

<wildcard/>

例如:我想获取所有行,其中包含带有通配符的ID为1000和1001的特征。这意味着必须有两个字符串

<characteristic id="1001" ...
  <wildcard/>
  ...
</characteristic>

<characteristic id="1000" ...
  <wildcard/>
  ...
</characteristic>

在里面。因此,这两个字符串可以有不同的顺序。

1 个答案:

答案 0 :(得分:2)

假设数据存储为XMLtype

select *
from   t
where  EXISTSNODE(doc,'/characteristics/characteristic[@id="1000"]/wildcard') = 1
  and  EXISTSNODE(doc,'/characteristics/characteristic[@id="1001"]/wildcard') = 1
;     

替代语法(由@Tomalak建议)

select *
from   t
where  EXISTSNODE(doc,'/characteristics[characteristic[@id="1001"]/wildcard and characteristic[@id="1010"]/wildcard]') = 1

出于学习目的,如果数据存储为字符串

select *
from   (select xmltype(doc) as doc from t)
where  EXISTSNODE(doc,'/characteristics/characteristic[@id="1000"]/wildcard') = 1
  and  EXISTSNODE(doc,'/characteristics/characteristic[@id="1001"]/wildcard') = 1
;