Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty namespace using Linq Xml

Tags:

xml

linq

I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";  XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),     new XElement(ns + "urlset",      new XElement("url",         new XElement("loc", "http://www.example.com/page"),         new XElement("lastmod", "2008-09-14")))); 

The result is ...

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">   <url xmlns="">     <loc>http://www.example.com/page</loc>     <lastmod>2008-09-14</lastmod>   </url> </urlset> 

I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?

like image 244
peterorum Avatar asked Sep 14 '08 03:09

peterorum


1 Answers

The "more correct way" would be:

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement(ns + "url",     new XElement(ns + "loc", "http://www.example.com/page"),     new XElement(ns + "lastmod", "2008-09-14")))); 

Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">   <url>     <loc>http://www.example.com/page</loc>     <lastmod>2008-09-14</lastmod>   </url> </urlset> 

which is, if I'm not mistaken, what you want.

like image 186
Micah Avatar answered Oct 15 '22 10:10

Micah