Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove xmlns from elements when generating XML with LINQ?

Tags:

c#

linq

I am trying to use LINQ to generate my Sitemap. Each url in the sitemap is generate with the following C# code:

XElement locElement = new XElement("loc", location);
XElement lastmodElement = new XElement("lastmod", modifiedDate.ToString("yyyy-MM-dd"));
XElement changefreqElement = new XElement("changefreq", changeFrequency);

XElement urlElement = new XElement("url");
urlElement.Add(locElement);
urlElement.Add(lastmodElement);
urlElement.Add(changefreqElement);

When I generate my sitemap, I get XML that looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url xmlns="">
    <loc>http://www.mydomain.com/default.aspx</loc>
    <lastmod>2011-05-20</lastmod>
    <changefreq>never</changefreq>
  </url>
</urlset>

My problem is, how do I remove the "xmlns=""" from the url element? Everything is correct except for this.

Thank you for your help!

like image 944
Villager Avatar asked May 20 '11 17:05

Villager


1 Answers

It sounds like you want the url element (and all subelements) to be in the sitemap namespace, so you want:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

XElement locElement = new XElement(ns + "loc", location);
XElement lastmodElement = new XElement(ns + "lastmod", modifiedDate.ToString("yyyy-MM-dd"));
XElement changefreqElement = new XElement(ns + "changefreq", changeFrequency);

XElement urlElement = new XElement(ns + "url");
urlElement.Add(locElement);
urlElement.Add(lastmodElement);
urlElement.Add(changefreqElement);

or more conventionally for LINQ to XML:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

XElement urlElement = new XElement(ns + "url",
    new XElement(ns + "loc", location);
    new XElement(ns + "lastmod", modifiedDate.ToString("yyyy-MM-dd"),
    new XElement(ns + "changefreq", changeFrequency));
like image 67
Jon Skeet Avatar answered Oct 23 '22 04:10

Jon Skeet