【问题标题】:Empty namespace using Linq Xml使用 Linq Xml 的空命名空间
【发布时间】:2023-04-07 17:39:01
【问题描述】:

我正在尝试使用 Linq to 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"))));

结果是……

<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 将其删除,但有没有更正确的方法?

【问题讨论】:

    标签: xml linq


    【解决方案1】:

    我在处理 VB.NET 中的类似问题时偶然发现了这篇文章。我使用的是 XML 文字,我花了一些时间来弄清楚如何使这个解决方案与 XML 文字构造一起工作,而不仅仅是功能构造。

    解决方法是在文件顶部导入 XML 命名空间。

    Imports <xmlns:ns="x-schema:tsSchema.xml">
    

    然后在查询表达式中为我所有的 XML 文字添加导入的命名空间的前缀。这将删除我保存输出时出现在元素上的空命名空间。

    Dim output As XDocument = <?xml version="1.0" encoding="utf-8"?>
                                  <XML ID="Microsoft Search Thesaurus">
                                      <thesaurus xmlns="x-schema:tsSchema.xml">
                                          <diacritics_sensitive>0</diacritics_sensitive>
                                          <%= From tg In termGroups _
                                              Select <ns:expansion>
                                                         <%= From t In tg _
                                                             Select <ns:sub><%= t %></ns:sub> %>
                                                     </ns:expansion> %>
                                      </thesaurus>
                                  </XML>
    
        output.Save("C:\thesaurus.xml")
    

    我希望这对某人有所帮助。尽管遇到这样的颠簸,XLinq API 还是非常酷的。

    【讨论】:

      【解决方案2】:

      “更正确的方法”是:

      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 中是很聪明的,所以结果是:

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

      如果我没记错的话,就是你想要的。

      【讨论】:

        【解决方案3】:

        如果一个元素使用一个命名空间,它们都必须使用一个。如果您没有自己定义一个,框架将添加一个空的命名空间,正如您所注意到的。而且,可悲的是,没有开关或类似的东西来抑制这个“功能”。

        所以,似乎没有更好的方法来去除它。使用 Replace(" xmlns=\"\"", "") 可能比执行 RegEx 快一点。

        【讨论】:

          猜你喜欢
          • 2011-01-21
          • 2020-04-06
          • 1970-01-01
          • 1970-01-01
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多