1

i want create sitemap.xml for google when i use "ns+" XNamespace insert to all nodes and output is under xml code xmlns="" is missing, how to create,please help me about create sitemap with asp.net and c# without i use foreach to read all news data and create url nodes dynamicaly

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url xmlns="">
    <loc>https://test.com/</loc>
    <lastmod>2022-05-21</lastmod>
    <priority>1.0</priority>
  </url>
</urlset>

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

            XDocument xDoc = new XDocument();

            var element = new XElement(ns + "urlset");

            element.Add(new XElement("url",

                  //Root Element
                  new XElement("loc", "https://test.com/"),
                  new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
                  new XElement("priority", "1.0"))

              );

            element.Add(new XElement("url",

                 //Root Element
                 new XElement("loc", "https://test.com/NewsList.aspx"),
                 new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
                 new XElement("priority", "1.0"))

             );

            element.Add(new XElement("url",

                 //Root Element
                 new XElement("loc", "https://test.com/NewsList.aspx?pn=0"),
                 new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
                 new XElement("priority", "1.0"))

             );

            foreach (var item in newsIds)
            {
                element.Add(new XElement("url",

                   //Root Element
                   new XElement("loc", "https://test.com/news.aspx?id=" + item),
                   new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
                   new XElement("priority", "1.0"))

               );
            }



            xDoc.Add(element);

            xDoc.Save(HttpContext.Current.Server.MapPath("~") + "sitemap.xml");

Xman
  • 23
  • 2
  • Not clear: is the result you are getting incorrect? I get the same result as at the top https://dotnetfiddle.net/bsjvqA – Charlieface May 22 '22 at 09:16
  • 1
    Perhaps you want `ns + "...` on each one, in other words you want them all to be part of that namespace. See https://stackoverflow.com/questions/30489117/specifiying-a-default-namespace-for-xdocument-gives-empty-value – Charlieface May 22 '22 at 09:23

1 Answers1

1

I found solution here:

How can I remove empty xmlns attribute from node created by XElement

var element = new XElement(ns + "urlset");
        element.Add(new XElement(ns + "url",

              //Root Element
              new XElement(ns + "loc", "https://test.com/"),
              new XElement(ns + "lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
              new XElement(ns + "priority", "1.0"))
          );
Mahdi
  • 649
  • 8
  • 18