I try to add a namespace on xml using WITH XMLNAMESPACES.
When I execute my queries, the namespace is added with the root element but with the second element I have xmlns="" as well... and I would like to remove that...
I provided an example:
Queries for creating the table and the data:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblTest](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](30) NOT NULL,
CONSTRAINT [PK_tblTest] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[tblTest] ON
INSERT [dbo].[tblTest] ([Id], [Name]) VALUES (1, N'Barack')
INSERT [dbo].[tblTest] ([Id], [Name]) VALUES (2, N'Nicolas')
INSERT [dbo].[tblTest] ([Id], [Name]) VALUES (3, N'Brian')
SET IDENTITY_INSERT [dbo].[tblTest] OFF
I generate the xml with these queries:
DECLARE @Xml xml
SET @Xml = (SELECT Id, Name
FROM dbo.tblTest
FOR XML PATH('Row'), ROOT('DataRows'));
WITH XMLNAMESPACES (DEFAULT 'http://www.mynamespace.com')
SELECT @Xml FOR XML PATH('Names');
Xml generated:
<Names xmlns="http://www.mynamespace.com">
<DataRows xmlns="">
<Row>
<Id>1</Id>
<Name>Barak</Name>
</Row>
<Row>
<Id>2</Id>
<Name>Nicolas</Name>
</Row>
<Row>
<Id>3</Id>
<Name>Brian</Name>
</Row>
</DataRows>
</Names>
So, I try this as well:
DECLARE @Xml xml
;WITH XMLNAMESPACES (DEFAULT 'http://www.mynamespace.com')
SELECT @Xml = (SELECT Id, Name
FROM dbo.tblTest
FOR XML PATH('Row'), TYPE);
;WITH XMLNAMESPACES (DEFAULT 'http://www.mynamespace.com')
SELECT @Xml
FOR XML PATH('DataRows'), ROOT('Names')
the xml generated is now:
<Names xmlns="http://www.mynamespace.com">
<DataRows>
<Row xmlns="http://www.mynamespace.com">
<Id>1</Id>
<Name>Barak</Name>
</Row>
<Row xmlns="http://www.mynamespace.com">
<Id>2</Id>
<Name>Nicolas</Name>
</Row>
<Row xmlns="http://www.mynamespace.com">
<Id>3</Id>
<Name>Brian</Name>
</Row>
</DataRows>
</Names>