2017-04-11 149 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