简体   繁体   中英

How do you remove xmlns from elements when generating XML with 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!

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM