Sql Server - XML碎化,其中定义了xmlns

时间:2014-05-01 16:27:57

标签: xml tsql sql-server-2008-r2 shred

如果在文档中定义了xmlns,我会破坏XML文件的问题:

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>'

我使用以下代码进行粉碎:

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);

当然这不起作用。虽然如果我删除

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" 

所以我最终只能使用&lt;&#39; Doc1&gt; select语句工作正常吗?我知道它与命名空间有关,但我根本无法找到解决这个问题的方法。提前谢谢。

1 个答案:

答案 0 :(得分:2)

Doc1及其子元素位于命名空间http://www.sample.com/file中。使用WITH XMLNAMESPACES将查询与此命名空间对齐:

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