views:

153

answers:

1

Considering this xml document:

DECLARE @X XML (DOCUMENT search.SearchParameters)  = '<parameters xmlns="http://www.educations.com/Search/Parameters.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  <parameter xsi:type="category" categoryID="38" />
</parameters>';

I'd like to access the value of the attribute "type".

According to this blog post, the xsi:type attribute is special and can't be accessed by usual keywords/functions.

How can I do it?

PS: I tried with

WITH XMLNAMESPACES (
 'http://www.educations.com/Search/Parameters.xsd' as p,
 'http://www.w3.org/2001/XMLSchema-instance' as xsi)
  SELECT @X.value('(/p:parameters/p:parameter/@xsi:type)[1]','nvarchar(max)')

but it didn't work.

A: 

Without specifying collection, this works fine for me:

DECLARE @X XML
SET @x = N' 
<parameters xmlns="http://www.educations.com/Search/Parameters.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
 <parameter  xsi:type="category" categoryID="38" />
</parameters>'
;

WITH    XMLNAMESPACES
        (
        'http://www.educations.com/Search/Parameters.xsd' as p,
        'http://www.w3.org/2001/XMLSchema-instance' as xsi
        )
SELECT  @X.value('(/p:parameters/p:parameter/@xsi:type)[1]','nvarchar(max)')

Could you please post contents of search.SearchParameters?

Update:

On schema-bound XML, this seems to be impossible.

You can cast your column into a freetype XML:

WITH    XMLNAMESPACES
        (
        'http://www.educations.com/Search/Parameters.xsd' as p,
        'http://www.w3.org/2001/XMLSchema-instance' as xsi
        )
SELECT  CAST(@X AS XML).value('(/p:parameters/p:parameter/@xsi:type)[1]','nvarchar(max)')

(but you won't be able to use XML indexes of any on your column), or perform a boolean check on a specific type:

WITH XMLNAMESPACES
        (
        'http://www.educations.com/Search/Parameters.xsd' as p
        )
SELECT @X.query('(/p:parameters/p:parameter)[1] instance of element(*, p:category?)')
Quassnoi
Unlucky the column in the db has the schema set.Here is the content of the schema (i removed other subtypes of the type "parameter")http://snipt.org/Gogk
Kralizek