使用Linq Xml的空命名空间

pet*_*rum 32 xml linq

我正在尝试使用Linq到Xml创建一个站点地图,但我得到一个空的命名空间属性,我想摆脱它.例如

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
    new XElement(ns + "urlset",

    new XElement("url",
        new XElement("loc", "http://www.example.com/page"),
        new XElement("lastmod", "2008-09-14"))));
Run Code Online (Sandbox Code Playgroud)

结果是......

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url xmlns="">
    <loc>http://www.example.com/page</loc>
    <lastmod>2008-09-14</lastmod>
  </url>
</urlset>
Run Code Online (Sandbox Code Playgroud)

我宁愿在url元素上没有xmlns ="".我可以在最终的xdoc.ToString()上使用Replace来删除它,但是有更正确的方法吗?

Mic*_*cah 43

"更正确的方式"是:

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
new XElement(ns + "urlset",
new XElement(ns + "url",
    new XElement(ns + "loc", "http://www.example.com/page"),
    new XElement(ns + "lastmod", "2008-09-14"))));
Run Code Online (Sandbox Code Playgroud)

与您的代码相同,但在每个要在sitemap命名空间中的元素名称之前使用"ns +".它足够聪明,不会在生成的XML中放置任何不必要的命名空间声明,因此结果如下:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/page</loc>
    <lastmod>2008-09-14</lastmod>
  </url>
</urlset>
Run Code Online (Sandbox Code Playgroud)

也就是说,如果我没弄错的话,你想要什么.