使用LINQ生成XML时,如何从元素中删除xmlns?

6

我正在尝试使用LINQ生成我的网站地图。每个网址都是用以下C#代码生成的:

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 =”“”?除此之外,一切都正确。
感谢您的帮助!
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接