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

2023-12-28

我正在尝试使用 LINQ 生成我的站点地图。站点地图中的每个 url 都是使用以下 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=”“”?除了这一点之外,一切都是正确的。

感谢您的帮助!


听起来你想要url元素(和所有子元素)be在站点地图命名空间中,因此您需要:

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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 LINQ 生成 XML 时如何从元素中删除 xmlns? 的相关文章

随机推荐