declare @myDoc xml
set @myDoc = '<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.mydomain.org/MySchema.xsd" SectionId="ABCD" Description="Some stuff">
<ProductDescription ProductID="1" ProductName="Road Bike">
<Features>
<Warranty>1 year parts and labor</Warranty>
<Maintenance>3 year parts and labor extended maintenance is available</Maintenance>
</Features>
</ProductDescription>
</Form>'
;WITH XMLNAMESPACES( 'http://www.w3.org/2001/XMLSchema-instance' as xsi, 'http://www.w3.org/2001/XMLSchema' as xsd, DEFAULT 'http://www.mydomain.org/MySchema.xsd' )
SELECT @myDoc.value('/Form[@SectionId][0]', 'varchar')
我需要获取SectionId的属性值作为nvarchar吗?我该怎么做?...
T和R. 标记
答案 0 :(得分:1)
你可以写得更简单:
;WITH XMLNAMESPACES(DEFAULT 'http://www.mydomain.org/MySchema.xsd')
SELECT @myDoc.value('(/Form/@SectionId)[1]', 'VARCHAR(100)') AS SectionId
由于您从未使用/引用任何xsi
或xsd
命名空间,因此无需声明这些命名空间。
由于您只从一个元素中获取一个属性,因此使用.nodes()
函数创建内部“虚拟表”也没有意义。
答案 1 :(得分:0)
;WITH XMLNAMESPACES( 'http://www.w3.org/2001/XMLSchema-instance' as xsi, 'http://www.w3.org/2001/XMLSchema' as xsd, DEFAULT 'http://www.mydomain.org/MySchema.xsd' )
SELECT Node.value('@SectionId', 'VARCHAR(100)') AS SectionId
FROM @myDoc.nodes('/Form') TempXML (Node);