How to remove xmlns from elements when generating XML using LINQ?

I am trying to use LINQ to create my Sitemap. Each URL in the Sitemap is generated with the following C # code:

XElement locElement = new XElement("loc", location); XElement lastmodElement = new XElement("lastmod", modifiedDate.ToString("yyyy-MM-dd")); XElement changefreqElement = new XElement("changefreq", changeFrequency); XElement urlElement = new XElement("url"); urlElement.Add(locElement); urlElement.Add(lastmodElement); urlElement.Add(changefreqElement); 

When I create my Sitemap, I get an XML that looks like this:

 <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url xmlns=""> <loc>http://www.mydomain.com/default.aspx</loc> <lastmod>2011-05-20</lastmod> <changefreq>never</changefreq> </url> </urlset> 

My problem is how to remove "xmlns =" ​​"" from the url element? Everything is correct except for this.

Thank you for your help!

+6
source share
1 answer

It sounds like you want an element url (and all sub-elements) located in the space sitemap names, so you want to:

 XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XElement locElement = new XElement(ns + "loc", location); XElement lastmodElement = new XElement(ns + "lastmod", modifiedDate.ToString("yyyy-MM-dd")); XElement changefreqElement = new XElement(ns + "changefreq", changeFrequency); XElement urlElement = new XElement(ns + "url"); urlElement.Add(locElement); urlElement.Add(lastmodElement); urlElement.Add(changefreqElement); 

or more conditionally for LINQ to XML:

 XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XElement urlElement = new XElement(ns + "url", new XElement(ns + "loc", location); new XElement(ns + "lastmod", modifiedDate.ToString("yyyy-MM-dd"), new XElement(ns + "changefreq", changeFrequency)); 
+6
source

Source: https://habr.com/ru/post/888663/


All Articles