使用Linq Xml的空名称空间 [英] Empty namespace using Linq Xml

查看:90
本文介绍了使用Linq Xml的空名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.

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

结果是...

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

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

I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?

推荐答案

更正确的方式"是:

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

与您的代码相同,但每个需要在站点地图名称空间中的元素名称前均带有"ns +".它足够聪明,不会在结果XML中放置任何不必要的名称空间声明,因此结果是:

Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is:

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

如果我没记错的话,那就是你想要的东西.

which is, if I'm not mistaken, what you want.

这篇关于使用Linq Xml的空名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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