【问题标题】:XML DML query for attribute属性的 XML DML 查询
【发布时间】:2010-11-11 09:59:21
【问题描述】:
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 标记

【问题讨论】:

    标签: tsql xquery-sql xml-dml


    【解决方案1】:

    你可以写得更简单:

    ;WITH XMLNAMESPACES(DEFAULT 'http://www.mydomain.org/MySchema.xsd')
    SELECT @myDoc.value('(/Form/@SectionId)[1]', 'VARCHAR(100)') AS SectionId
    

    由于您从未使用/引用任何 xsixsd 命名空间,因此无需声明它们。

    而且由于您只从一个元素中获取一个属性,因此使用.nodes() 函数来创建内部“虚拟表”也没有任何意义。

    【讨论】:

    • 谢谢马克,但我没有添加命名空间,xml 的生产者这样做了,所以我必须保留它们,因为 SELECT 没有它们就返回 NULL。真正的 xml 实际上存储在无类型的 xml 列中,而不是 xml 类型的变量。我正在使用 .nodes() 因为我不能保证只有一个。但我明白你的意思。
    【解决方案2】:
    ;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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多