【问题标题】:Cannot add "xmlns" attribute to urlset in sitemap.xml无法将“xmlns”属性添加到 sitemap.xml 中的 urlset
【发布时间】:2014-08-13 12:31:40
【问题描述】:

我生成了一个sitemap.xml

XDocument xDoc = new XDocument(
    new XDeclaration("1.0", "UTF-8", ""),
    new XElement("urlset",
    new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),
    new Element (....and so on...)

我收到一个错误

前缀 '' 不能在同一起始元素标记中从 '' 重新定义为 'http://www.sitemaps.org/schemas/sitemap/0.9'。

Google 要求 xmlns 属性不带任何前缀。

【问题讨论】:

  • xmlns 实际上不是一个属性。这是一个命名空间声明。它们看起来很相似,但 XML 认为它们是不同类型的东西,因此您不应该期望使用精心设计的 XML 库中的属性操作代码来操作它们。

标签: c# xml xml-namespaces xml-sitemap


【解决方案1】:

似乎在XDocument 中添加默认命名空间有点棘手,相关问题:How to set the default XML namespace for an XDocument

您可以尝试声明默认命名空间前缀并将该前缀用于<urlset> 中的所有元素,如下所示:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xDoc = new XDocument(
    new XDeclaration("1.0", "UTF-8", ""),
    new XElement(ns+"urlset",
    new XElement(ns+"otherElement"),
    new XElement (....and so on...)

【讨论】:

    【解决方案2】:

    你可以通过使用空白命名空间来解决这个问题,如下所示:

        XNamespace blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9");
    
        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement(blank + "urlset",
                new XAttribute("xmlns", blank.NamespaceName),  
                new XElement(blank + "loc", "http://www.abc.eba/"),               
                new Element (....and so on...)
             ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多