如果在文档中定义了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语句工作正常吗?我知道它与命名空间有关,但我根本无法找到解决这个问题的方法。提前谢谢。
答案 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);