SQLServer:阻止访问查询数据的命名空间

时间:2010-03-31 13:57:53

标签: sql-server xml namespaces

一个初学者的问题,希望很容易回答。我有一个xml文件,我想加载到SQLServer 2008并提取有用的信息。

我开始简单,只是尝试提取名称(\ gpx \ name)。我的代码是:

DECLARE @x xml;
SELECT @x = xCol.BulkColumn
FROM OPENROWSET (BULK 'C:\Data\EM.gpx', SINGLE_BLOB) AS xCol;
-- confirm the xml data is in @x
select @x as XML_Data
-- try and get the name of the gpx section
SELECT 
     c.value('name[1]', 'varchar(200)') as Name
from @x.nodes('gpx') x(c)

以下是xml文件的大幅缩短版本:

<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0" creator="Groundspeak Pocket Query" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd" xmlns="http://www.topografix.com/GPX/1/0">
  <name>EM</name>
  <desc>Geocache file generated by Groundspeak</desc>
  <author>Groundspeak</author>
  <email>contact@groundspeak.com</email>
  <time>2010-03-24T14:01:36.4931342Z</time>
  <keywords>cache, geocache, groundspeak</keywords>
  <wpt lat="51.2586" lon="-2.213067">
    <time>2008-03-30T07:00:00Z</time>
    <name>GC1APHM</name>
    <desc>Sandman's Noble Hoard by Sandman1973, Unknown Cache (2/3)</desc>
    <groundspeak:cache id="832000" available="True" archived="False" xmlns:groundspeak="http://www.groundspeak.com/cache/1/0">
      <groundspeak:name>Sandman's Noble Hoard</groundspeak:name>
      <groundspeak:placed_by>Sandman1973</groundspeak:placed_by>
    </groundspeak:cache>
  </wpt>
</gpx>

如果前两行替换为:

<gpx>

上面的例子工作正常,但是我无法访问groundspeak:name(/ gpx / wpt / groundspeak:cache / groundspeak:name),所以我猜它是命名空间的问题。

任何帮助都会得到满足。

2 个答案:

答案 0 :(得分:0)

您必须声明命名空间。要么是这样的:

WITH XMLNAMESPACES ('http://www.topografix.com/GPX/1/0' as ns1)
SELECT c.value('ns1:name[1]', 'varchar(200)') as Name
  FROM @x.nodes('ns1:gpx') x(c)

或者像这样:

SELECT c.value('declare namespace ns1="http://www.topografix.com/GPX/1/0"; ns1:name[1]', 'varchar(200)') as Name
  FROM @x.nodes('declare namespace ns1="http://www.topografix.com/GPX/1/0"; ns1:gpx') x(c)

要使用groundspeak命名空间:

WITH XMLNAMESPACES ('http://www.topografix.com/GPX/1/0' as gpx, 'http://www.groundspeak.com/cache/1/0' as groundspeak)
SELECT c.value('(gpx:wpt/groundspeak:cache/groundspeak:name)[1]', 'nvarchar(max)')
  FROM @x.nodes('gpx:gpx') x(c)

答案 1 :(得分:0)

知道了,对erikkallen的答案进行了一些修改,我已经开始工作了:

;WITH XMLNAMESPACES ('http://www.topografix.com/GPX/1/0' as ns1) 
SELECT c.value('ns1:name[1]', 'varchar(200)') as Name 
  FROM @x.nodes('ns1:gpx') x(c) 

SELECT c.value('declare namespace ns1="http://www.topografix.com/GPX/1/0"; ns1:name[1]', 'varchar(200)') as Name 
  FROM @x.nodes('declare namespace ns1="http://www.topografix.com/GPX/1/0"; ns1:gpx') x(c) 

由于