2017-04-11 152 views
1

输入XML中提取XML:忽略某些节点

<Hierarchy><Relation> 
     <Child> 
     <Name>XYZ</Name> 
     <Age>10</Age> 
     </Child> 
     <IsEldest>True</IsEldest> 
     </Relation> 
     <Relation> 
     <Child> 
     <Name>ABC</Name> 
     <Age>5</Age> 
     </Child> 
     </Relation> 
     <Relation> 
     <Child> 
     <Name>PQR</Name> 
     <Age>3</Age> 
     </Child> 
     </Relation></Hierarchy> 

预期结果:

  <Relation> 
     <Child> 
     <Name>ABC</Name> 
     <Age>5</Age> 
     </Child> 
     </Relation> 
     <Relation> 
     <Child> 
     <Name>PQR</Name> 
     <Age>3</Age> 
     </Child> 
     </Relation> 

我们怎样才能在一个SQL XML查询使用SQL Server检索预期的结果。 应该提取没有IsEldest标签的节点。 使用@ xml.modify可以选择删除与IsEldes节点的关系标记。但任何其他方法提取所需的XML?

+0

其他e是''的出现,其值为“真”以外的值?在这种情况下应该发生什么? – Shnugo

回答

2
@xml.query('//Relation[not(IsEldest[1]="True")]') 
+0

我完全误解了这个问题+1在我身边! – Shnugo

+0

谢谢Jeroen,这个工程。我正在尝试@ xml.query('// Relation [(IsEldest [1]!=“True”)]'),显然它不起作用。 – Kapil

1

你可以用一个XQuery表达FLWOR方法:

DECLARE @xml XML= 
'<Hierarchy> 
    <Relation> 
    <Child> 
     <Name>XYZ</Name> 
     <Age>10</Age> 
    </Child> 
    <IsEldest>True</IsEldest> 
    </Relation> 
    <Relation> 
    <Child> 
     <Name>ABC</Name> 
     <Age>5</Age> 
    </Child> 
    </Relation> 
    <Relation> 
    <Child> 
     <Name>PQR</Name> 
     <Age>3</Age> 
    </Child> 
    </Relation> 
</Hierarchy>'; 

--The查询(根据TT编辑的评论)

SELECT @xml.query 
(N' 
    <Relation> 
    { 
    for $c in /Hierarchy/Relation[not(IsEldest[1]="True")]/Child 
    return $c 
    } 
    </Relation> 
'); 

结果

<Relation> 
    <Child> 
    <Name>ABC</Name> 
    <Age>5</Age> 
    </Child> 
    <Child> 
    <Name>PQR</Name> 
    <Age>3</Age> 
    </Child> 
</Relation> 
+0

@TT。 Thx,我完全误解了这个问题! Jeroen的回答比较好... – Shnugo