0

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496
podeig
  • 2,597
  • 8
  • 36
  • 60
  • `xmlns` isn't, actually, an attribute. It's a namespace declaration. They look similar but XML considers them to be a different type of thing, so you shouldn't expect to manipulate them using attribute manipulation code in well-designed XML libraries. – Damien_The_Unbeliever Aug 13 '14 at 13:56

2 Answers2

0

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...)
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
0

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...)
         ));
Mustafa Çakıroğlu
  • 1,618
  • 1
  • 11
  • 10