使用LINQ生成XML时,如何从元素中删除xmlns? [英] How do you remove xmlns from elements when generating XML with LINQ?

查看:79
本文介绍了使用LINQ生成XML时,如何从元素中删除xmlns?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

生成站点地图时,我得到的XML如下所示:

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>

我的问题是,如何从url元素中删除"xmlns ="?除此之外,一切都是正确的.

My problem is, how do I remove the "xmlns=""" from the url element? Everything is correct except for this.

谢谢您的帮助!

推荐答案

听起来好像您希望Sitemap名称空间中的url元素(以及所有子元素)成为 be ,所以您需要:

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

或更常规地用于LINQ to XML:

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

这篇关于使用LINQ生成XML时,如何从元素中删除xmlns?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆