无法在sitemap.xml中为urlset添加 "xmlns "属性。

问题描述 投票:0回答:2

我生成了一个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.orgschemassitemap0.9'在同一个开始元素标签内。

Google要求xmlns属性不加任何前缀,我生成了sitemap.xml XDocument xDoc = new XDocument( 新的XDeclaration("1.0"),"UTF-8","1.0"。

c# xml xml-namespaces xml-sitemap
2个回答
0
投票

看来,将默认的命名空间添加到 XDocument 是一个有点棘手的,相关的问题.如何为XDocument设置默认的XML命名空间?如何为XDocument设置默认的XML命名空间?

您可以尝试声明默认的命名空间前缀,并将该前缀用于在 <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...)

0
投票

你可以通过使用空白的命名空间来解决这个问题,就像下面这样。

    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...)
         ));
© www.soinside.com 2019 - 2024. All rights reserved.