質問

I have problem shredding an XML file if xmlns is defined in a document as seen here:

DECLARE @XML XML 
SET @XML=N'
<Doc1 xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-    instance"   xsi:schemaLocation="http://www.sample.com/file/long/path.xsd">
    <header>
        <stuff>data</stuff>
        <morestuff>data</morestuff>
    </header>
 </Doc1>'

I use following code for shredding:

SELECT 
T.c.query('stuff').value('.', 'char(50)') AS stuff1,
T.c.query('morestuff').value('.', 'VARCHAR(20)') AS morestuff
FROM @XML.nodes('Doc1/header') AS T(c);

Which of course would not work. Although if I remove

xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-    instance"   xsi:schemaLocation="http://www.sample.com/file/long/path.xsd" 

so I will end up only with <'Doc1> the select statement works fine? I know it has something to do with namespaces but I simply cannot find a solution to this problem. Thank you in advance.

役に立ちましたか?

解決

Doc1 and its sub elements are in the namespace http://www.sample.com/file. Use WITH XMLNAMESPACES to align the query with this namespace:

DECLARE @XML XML;
SET @XML=N'
<Doc1 xmlns="http://www.sample.com/file" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-    instance"   
      xsi:schemaLocation="http://www.sample.com/file/long/path.xsd">
    <header>
        <stuff>data</stuff>
        <morestuff>data</morestuff>
    </header>
 </Doc1>';

WITH XMLNAMESPACES('http://www.sample.com/file' as x)
SELECT 
T.c.query('x:stuff').value('.', 'char(50)') AS stuff1,
T.c.query('x:morestuff').value('.', 'VARCHAR(20)') AS morestuff
FROM @XML.nodes('x:Doc1/x:header') AS T(c);

SqlFiddle Here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top