2014-01-23 68 views
1

使用以下XML,在SQL Server中,如何獲取LineItemId,PetId(值),vetid(Value)的表?我很難過。XML XPath - 子路徑

基本上,它應該返回:

255fa32c-dce6-4e7a-83a5-4b45f22f00fc 75866 12916 
183dc279-53a6-45fc-9e75-57770582b6bc 34535 34546 

從這個XML:

<PurchaseOrder> 
    <OrderForms> 
    <OrderForm> 
     <LineItems> 
     <LineItem LineItemId="255fa32c-dce6-4e7a-83a5-4b45f22f00fc"> 
      <WeaklyTypedProperties> 
      <WeaklyTypedProperty Name="petId" Value="75866" Type="String" /> 
      <WeaklyTypedProperty Name="vetId" Value="12916" Type="String" /> 
      </WeaklyTypedProperties> 
     </LineItem> 
     <LineItem LineItemId="183dc279-53a6-45fc-9e75-57770582b6bc"> 
      <WeaklyTypedProperties> 
      <WeaklyTypedProperty Name="petId" Value="345345" Type="String" /> 
      <WeaklyTypedProperty Name="vetId" Value="345346" Type="String" /> 
      </WeaklyTypedProperties> 
     </LineItem> 
     </LineItems> 
    </OrderForm> 
    </OrderForms> 
</PurchaseOrder> 

我應該說明我曾嘗試以下,但它給毛坯petId和vetId:

SELECT 
    p.value('@LineItemId','NVARCHAR(100)') 
    ,p.query('//PurchaseOrder/OrderForms/OrderForm[1]/LineItems/LineItem[1]/WeaklyTypedProperties/WeaklyTypedProperty[Name="petId"]') 
    ,p.query('//PurchaseOrder/OrderForms/OrderForm[1]/LineItems/LineItem[1]/WeaklyTypedProperties/WeaklyTypedProperty[Name="vetid"]') 
FROM 
    dbo.[PurchaseOrdersMarshalledData] pomd 
    CROSS APPLY pomd.[MarshalledData].nodes('//PurchaseOrder/OrderForms/OrderForm[1]/LineItems/LineItem') x(p) 

謝謝!

+0

也許你缺少給它的一個屬性名稱@? – dbermudez

+0

我不知道SQL Server,但普通的XPath 2.0它可能類似'// LineItem/concat(@LineItemId,'',string-join(。/ WeaklyTypedProperty/@ Value,''))' – acdcjunior

回答

0
SELECT 
    [LineItemId] = l.value('@LineItemId', 'nvarchar(100)'), 
    [PetId] = w.value('WeaklyTypedProperty[@Name="petId"][1]/@Value', 'int'), 
    [VetId] = w.value('WeaklyTypedProperty[@Name="vetId"][1]/@Value', 'int') 
FROM dbo.[PurchaseOrdersMarshalledData] pomp 
CROSS APPLY pomp.[MarshalledData].nodes('//PurchaseOrder/OrderForms/OrderForm[1]/LineItems/LineItem') LineItem(l) 
CROSS APPLY l.nodes('WeaklyTypedProperties') WeaklyTypedProperty(w) 
+0

您搖滾。正是我需要的。 – user3229881

0

還沒有嘗試過......也許大成是不是100%正確...

<xsl:for-each select="/PurcharseOrder/OrderForms/OrderForm/LineItems/LineItem"/> 
    <xsl:value-of select="@LineItemId"/> 
    <xsl:for-each select="WeaklyTypedProperties"/> 
     <xsl:value-of select="WeaklyTypedProperty/@Value"/> 
    </xsl:for-each> 
</xsl:for-each> 
+0

Can not您將'// PurcharseOrder/OrderForms/OrderForm/LineItems/LineItem'縮短爲'// LineItem'? – Robin

+0

我以爲你想要XSLT,還沒有讀過SQL-Server部分。我留下XSLT模板以防萬一它給你一些提示! – dbermudez

+0

我認爲從根節點訪問更爲正確,以防萬一您在XML文檔的其他部分中有LineItem節點(並且您不想處理它們) – dbermudez