如何从XML片段中提取数据?

时间:2014-04-07 16:54:18

标签: sql sql-server xml sql-server-2005

我有以下代码:

declare @BillingAddresses xml
set @BillingAddresses=convert(xml,N'
<BillingAddresses>
  <BillingAddress Address1="P.O. Box 2162" City="Huntington Beach"/>
  <BillingAddress Address1="12933 Monarch" City="Aliso Viejo"/>
  <BillingAddress Address1="6666 Von Karman Ave" City="Irvine"/>
</BillingAddresses>')


SELECT
    Addr.Col.value('Address1[1]', 'varchar(100)'),  
    Addr.Col.value('City[1]', 'varchar(100)')
FROM @BillingAddresses.nodes('/BillingAddresses/BillingAddress') Addr(Col)

我得到所有的NULL。如何从XML片段中获取Address1和City属性?

1 个答案:

答案 0 :(得分:2)

要访问XML元素属性,您必须使用适当的XPath语法。

declare @BillingAddresses xml
set @BillingAddresses=convert(xml,N'
<BillingAddresses>
  <BillingAddress Address1="P.O. Box 2162" City="Huntington Beach"/>
  <BillingAddress Address1="12933 Monarch" City="Aliso Viejo"/>
  <BillingAddress Address1="6666 Von Karman Ave" City="Irvine"/>
</BillingAddresses>')


SELECT
    Addr.Col.value('@Address1', 'varchar(100)'),  
    Addr.Col.value('@City', 'varchar(100)')
FROM @BillingAddresses.nodes('/BillingAddresses/BillingAddress') Addr(Col)