我正在使用SQL Server 2008 R2来解析XML,但它没有返回结果:
<?xml version="1.0" encoding="UTF-8"?>
<ymaps xmlns="http://maps.yandex.ru/ymaps/1.x" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://maps.yandex.ru/business/1.x http://maps.yandex.ru/schemas/business/1.x/business.xsd http://maps.yandex.ru/geocoder/1.x http://maps.yandex.ru/schemas/geocoder/1.x/geocoder.xsd http://maps.yandex.ru/psearch/1.x http://maps.yandex.ru/schemas/psearch/1.x/psearch.xsd http://maps.yandex.ru/search/1.x http://maps.yandex.ru/schemas/search/1.x/search.xsd http://maps.yandex.ru/web/1.x http://maps.yandex.ru/schemas/web/1.x/web.xsd http://maps.yandex.ru/search/internal/1.x ../../search/internal/1.x/internal.xsd">
<Attribution xmlns="http://maps.yandex.ru/attribution/1.x" />
<GeoObjectCollection>
<featureMember xmlns="http://www.opengis.net/gml">
<GeoObject xmlns="http://maps.yandex.ru/ymaps/1.x">
<Point xmlns="http://www.opengis.net/gml">
<pos>47.248887 56.143900</pos>
</Point>
</GeoObject>
</featureMember>
</GeoObjectCollection>
</ymaps>
代码:
SELECT @XML.value('(/ymaps/GeoObjectCollection/featureMember/GeoObject/Point/pos) [1]', 'varchar(255)')
还有其他好办法吗?谢谢。
答案 0 :(得分:0)
你有两个可能的问题:
1)您缺少XPath表达式中的命名空间,因此它不匹配。
2)表达式和谓词之间有空格。
尝试改为:
SELECT @XML.value('(/*:ymaps/*:GeoObjectCollection/*:featureMember/*:GeoObject/*:Point/*:pos)[1]', 'varchar(255)')
我不知道如何轻松管理MSSQL XML中的命名空间,因此我使用了*
,这意味着任何命名空间。
答案 1 :(得分:0)
您在XML的各个级别中声明了两个不同的默认命名空间。请注意,给定默认命名空间,默认命名空间声明的元素及其所有没有前缀且没有不同默认命名空间的后代都被视为在同一命名空间内。
您可以使用;WITH XMLNAMESPACES()
注册默认名称空间和名称空间前缀:
;WITH XMLNAMESPACES ('http://www.opengis.net/gml' as ns,
DEFAULT 'http://maps.yandex.ru/ymaps/1.x')
SELECT @XML.value('(/ymaps/GeoObjectCollection/ns:featureMember/GeoObject/ns:Point/ns:pos) [1]', 'varchar(255)')
<强> SQL Fiddle 强>