Pages

Tuesday, 15 May 2012

Default Namespaces in XDocument


Trying to create a google news site map using XDocument yesterday and I ran into a little problem working with a default namespace as well as additional explicitly named namespaces.

i.e <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
To save you guys the time and effort here is some advice - you need to declare the default namespace in the root element name declaration and add additional namespaces as Attributes to this element.
See below snippet of code:
XNamespace sitemap = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9"); 
XNamespace news = XNamespace.Get("http://www.google.com/schemas/sitemap-news/0.9");  
XDocument newsSitemapDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null),                 
new XElement(sitemap + "urlset",
new XAttribute(XNamespace.Xmlns + "news", news.NamespaceName)));

No comments:

Post a Comment