SolutionCottage.com
Posted  30 Oct 2008 - 13:11:37

Category: XML


AppendChild creates empty namespace declaration

Issue:
Remove default namespace added by AppendChild.

Solution:
I encountered this issue when making a sitemap for Google in ASP.net. The format of the XML is described here

I created the sitemap as a new XmlElement and the loc and lastmod via the innerXml property. When I used AppendChild to attach this XmlElement to the XmlDocument, there was a namespace definition added like this: xmlns="". If you use this as your google sitemap you will get a warning about this.

To solve this problem, you have to set the namespace to the same as the parent. So rather than using innerXml to create the loc and lastmod tags you have to use XMlElements and set their namespaces to the same. Here is an example:

Dim xDoc As New XmlDocument
Dim xDecl As XmlDeclaration = Nothing
xDecl = xDoc.CreateXmlDeclaration("1.0", "UTF-8", String.Empty)
xDoc.AppendChild(xDecl)

Dim xRootEl As XmlElement = xDoc.CreateElement("sitemapindex", "http://www.google.com/schemas/sitemap/0.84")
xDoc.InsertAfter(xRootEl, xDecl)

Dim xEl As XmlElement = xDoc.CreateElement("sitemap", "http://www.google.com/schemas/sitemap/0.84")

Dim xLoc As XmlElement = xDoc.CreateElement("loc", "http://www.google.com/schemas/sitemap/0.84")
xLoc.InnerText = "http://localhost/sitemap.xml"

Dim xLastmod As XmlElement = xDoc.CreateElement("lastmod", "http://www.google.com/schemas/sitemap/0.84")
xLastmod.InnerText = "2008-10-30T09:47:00+00:00"

xRootEl.AppendChild(xEl)

xEl.AppendChild(xLoc)
xEl.AppendChild(xLastmod)



Marked as helpful by 6 users




0 comments:








© SolutionCottage 2008-2011 9/26/2017 10:06:25 AM