1

I have the below XML output generated using a SQL Server query (added in the rextester link):

<Main>
    <ID>1001</ID>
    <details>
        <name>John</name>
        <age>12</age>
    </details>
</Main>

I want to know how to add a namespace xmlns:json="http://www.samplenamespace.com/json" to the Main node.

Desired output:

<Main xmlns:json="http://www.samplenamespace.com/json">
    <ID>1001</ID>
    <details>
        <name>John</name>
        <age>12</age>
    </details>
</Main>

Rextester link: http://rextester.com/OQZH6668

Any help!?

1 Answer 1

3

You need to use the WITH XMLNAMESPACES clause, for example:

---Fake tables in Stored procedure1
create table #Cdetails(cid int, name varchar(5), age int)
insert into #Cdetails
values(1001,'John',12),
(1002,'Rick',19),
(1003,'Diane',25),
(1004,'Kippy',26)

--Output of Stored procedure 

create table #final(xml_data xml)
insert into #final
select
XML_data =  
    (select ID = cd1.cid,
    details =
        (
        select cd.name,
        cd.age
        from #Cdetails cd
        where cd.cid = cd1.cid
        For XML Path(''), Type)
    from #Cdetails cd1
    For XML Path('Main'));


WITH XMLNAMESPACES ('http://www.samplenamespace.com/json' as json)  
select * from #final
For XML Path('Main')

drop table #Cdetails,#final

Note the extra ; that is required when using WITH statements.

Rextester link: http://rextester.com/EBLL48414

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How can I add a property like 'json:ValueType="Number" ' to a node? I want to add <age json:ValueType="Number">12</age>. Can you sample that one too?
Understand. I was doubtful if that question may be closed saying it's redundant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.