podeig
podeig

Reputation: 2741

Cannot add "xmlns" attribute to urlset in sitemap.xml

I generate a 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...)

I get an error

The prefix '' cannot be redefined from '' to 'http://www.sitemaps.org/schemas/sitemap/0.9' within the same start element tag.

Google requires xmlns attribute without any prefix.

Upvotes: 0

Views: 1802

Answers (2)

Mustafa Çakıroğlu
Mustafa Çakıroğlu

Reputation: 1658

You can solve this problem by using blank namespace like the following:

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

Upvotes: 0

har07
har07

Reputation: 89285

Seems that adding default namespace in XDocument is a bit tricky, related question : How to set the default XML namespace for an XDocument

You can try to declare default namespace prefix and use that prefix for all elements within <urlset> like so :

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

Upvotes: 0

Related Questions