首页 > 解决方案 > C# xml 站点地图如何从 url 部分消除 xmlns

问题描述

这个问题与XML 站点地图从 url 标记中删除 xmlns相同,但从未得到回答。现在我的xml返回如下

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url xmlns="">
<loc>https://www.localhost.com/J-B-Lansing-Co-CA/1/Hsuhsus</loc>
</url>
<url xmlns="">
<loc>
https://www.localhost.com/J-B-Lansing-Co-CA/2/Swhuwhsw-wshwshusws
</loc>
</url>
</urlset>

我在这里专注于这部分<url xmlns="">我需要删除 xmlns 部分并且没有成功。我的代码如下

       [Route("sitemap")]
        public async Task<ContentResult> SiteMap()
        {
            var result = await _homeRepository.URLMapper();


            XNamespace nsSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var urlSet = new XElement(nsSitemap + "urlset",
                result.Select(x =>
                    new XElement("url",
                       new XElement("loc", x.URL))));


            return new ContentResult
            {
                ContentType = "text/xml",
                Content = urlSet.ToString(),
                StatusCode = 200
            };
        }

结果 url 映射器只是从数据库中返回一个 url 列表。任何建议都会很棒。

标签: c#xmlasp.net-core

解决方案


您需要在这些XElement名称前面加上命名空间:这演示了解决方案:

XNamespace nsSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var urlSet = new XElement(
                nsSitemap + "urlset",
                new[] { new { URL = "https://www.localhost.com/J-B-Lansing-Co-CA/1/Hsuhsus" }}
                    .Select(x =>
                        new XElement(nsSitemap + "url",
                           new XElement(nsSitemap + "loc", x.URL)
                        )
                    )
            );
        Console.WriteLine(urlSet.ToString());

还创建了一个DotNetFiddle


推荐阅读