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));
精彩评论