2011-05-20 44 views
6

我想用LINQ来生成我的站点地图。在网站地图中的每个URL与下面的C#代码生成:如何在使用LINQ生成XML时从元素中删除xmlns?

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

当我生成我的地图,我得到XML,看起来像以下:

<?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> 

我的问题是,我怎么删除“url”元素中的“xmlns =”“”?除此之外,一切都是正确的。

谢谢你的帮助!

回答

6

这听起来像你想的url元素(及所有子元素),以在地图命名空间,所以你想:

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

或更多种常规的LINQ到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));