我有以下代码:
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属性?
答案 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)