2

I am trying to modify a stored proc to contain the following:

SET @XML = (    
    SELECT Category.Title,
        (       
            SELECT 'true' AS [@json:Array], Book.Name, Book.Value
            FROM @Book Book
            WHERE Category.CategoryID = Book.CategoryID
            FOR XML PATH('Values'), ROOT('Book'), TYPE
        ) 
    FROM @Category Category
    FOR XML PATH('Category'), ROOT('Response')
) 

The "SELECT 'true' AS [@json:Array]" is there to force the xml to add "json:Array='true' to the values node so that even if there's only one child element it will be contained in an array. But, the @json:Array throws an error: "XML name space prefix 'json' declaration is missing for FOR XML column name '@json:Array'."

I've looked at links like this but they all seem to deal with adding attributes that don't include a colon. I've also tried adding "WITH NAMESPACES..." but couldn't get the syntax right.

Can someone tell me how to modify the SQL to have this work?

Community
  • 1
  • 1
Danzig
  • 35
  • 11
  • Could you post sample data in http://sqlfiddle.com/ (more info: [Tips for asking a good Structured Query Language (SQL) question](http://meta.stackoverflow.com/questions/271055/tips-for-asking-a-good-structured-query-language-sql-question) – har07 Jan 26 '16 at 04:41
  • @Shnugo, you're absolutely right and I do apologise for the inattentiveness. And thank you for the vote :) – Danzig Feb 15 '16 at 00:39

1 Answers1

3

If you do it like this:

DECLARE @XML XML;
WITH XMLNAMESPACES('xmlns:json' AS json)
SELECT @XML=
(
    SELECT 'YourTitle',
        (       
            SELECT 'true' AS [@json:Array], 'BookName', 'BookValue'
            FOR XML PATH('Values'), ROOT('Book'), TYPE
        ) 
    FOR XML PATH('Category'), ROOT('Response')
) 
SELECT @xml

... you'll get the attribut. But the price is a repeated namespace in all of your root nodes (in nested too).

This might be a trick, but you'll have to declare your namespace in the top element:

DECLARE @XML XML;
SELECT @XML=
(
    REPLACE(REPLACE(
    (
    SELECT 'YourTitle',
        (       
            SELECT 'true' AS [@jsonArray], 'BookName', 'BookValue'
            FOR XML PATH('Values'), ROOT('Book'), TYPE
        ) 
    FOR XML PATH('Category'), ROOT('Response')
    ),'jsonArray','json:Array'),'<Response','<Response xmlns:json="urnJson"')
); 

SELECT @xml
Shnugo
  • 66,100
  • 9
  • 53
  • 114
  • 1
    Thanks Shnugo - your suggestion got me to my solution. Here's what worked for me: ` ;WITH XMLNAMESPACES('http://james.newtonking.com/projects/json' AS json) SELECT @XML = ( SELECT 'true' AS '@json:Array', Category.Title, ( SELECT 'true' AS '@json:Array', Book.Name, Book.Value FROM @Book Book WHERE Category.CategoryID = Book.CategoryID FOR XML PATH('Values'), ROOT('Book'), TYPE ) FROM @Category Category FOR XML PATH('Category'), ROOT('Response') ) ` The james.newtonking.com namespace seemed to be required. – Danzig Feb 15 '16 at 00:33