I'm trying to get value of cat but it retuns me null. Please, help me to get this value. Thanks in advance!

DECLARE @xml XML 
SET @xml = '
<cat:catalog xmlns:cat="http://datypic.com/cat"
             xmlns:prod="http://datypic.com/prod">
  <cat:number>1446</cat:number>
  <prod:product>
    <prod:number>563</prod:number>
    <prod:name prod:language="en">Floppy Sun Hat</prod:name>
  </prod:product>
</cat:catalog>'

Select @xml.value('declare namespace ns="xmlns:cat=http://datypic.com/cat"; /ns:cat[1]/number[1]', 'int')
有帮助吗?

解决方案

You are trying to grab "cat[1]" but there is no element "cat", it is only a prefix. You want "catalog" I believe. Also, you must namespace prefix the "number" child as well. And the way you wrote declare namespace is I believe incorrect as well. No need for "xmlns:cat=" in there.

In other words:

Select @xml.value('declare namespace ns="http://datypic.com/cat"; /ns:catalog[1]/ns:number[1]', 'int')

...ought to work. But podiluska's prefix change is more suitable since "ns" doesn't give any hint about what namespace you are using. The important thing to bear in mind is that the prefix is arbitrary (it could be anything), but you have to tie it to whatever element you want in that namespace.

其他提示

Try

Select @xml.value('declare namespace cat="http://datypic.com/cat"; 
    (/cat:catalog/cat:number)[1]','int')

You can also do this using WITH XMLNAMESPACES, which makes the namespace declarations apply across the whole statement, rather than a single call to .value. This is useful if you need to get multiple values from the XML, eg

DECLARE @xml XML  
SET @xml = '<cat:catalog xmlns:cat="http://datypic.com/cat" xmlns:prod="http://datypic.com/prod">
  <cat:number>1446</cat:number>
  <prod:product>
    <prod:number>563</prod:number>
    <prod:name prod:language="en">Floppy Sun Hat</prod:name>
  </prod:product>
</cat:catalog>' 

;WITH XMLNAMESPACES (
'http://datypic.com/cat' AS cat,
'http://datypic.com/prod' AS prod
)
SELECT 
    c.c.value('(cat:number/text())[1]', 'INT') 'cat:number',
    p.c.value('(prod:number/text())[1]', 'INT') 'prod:number',
    p.c.value('(prod:name/@prod:language)[1]', 'VARCHAR(2)') 'prod:language',
    p.c.value('(prod:name/text())[1]', 'VARCHAR(50)') 'prod:name'
FROM @xml.nodes('cat:catalog') c(c)
    CROSS APPLY c.c.nodes('prod:product') p(c)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top