This document already has a ‘ DocumentElement ‘ node

I faced this exception while trying to generate a xml document programmatically in C# using XmlDocument and XmlElement.

I didn’t know what was going on, and then I figured out that I was adding multiple elements to the XmlDocument. To solve this, add a “root” element to XmlDocument and then add multiple child elements within the root. The XmlDocument is supposed to only contain 1 child element as expected in XML.

Firefox requests for XML format when performing a GET to Web API

Today while testing the Ext JS application I was writing on various browsers, something strange happened. The app works on IE and Chrome, while on Firefox it breaks.

It turns out if not configured correctly WebAPI will return data depending on the Accept HTTP header sent by browsers, and different browsers sent different HTTP Accept header.

More details in the SO answer: http://stackoverflow.com/a/31934984

Firefox prefers XML, so Web API try to serialize data in XML format to return to Firefox.

IE and Chrome doesn’t prefer one over other, so Web API chooses Json.

I solved this issue in Firefox by configuring the web api to always return JSON by adding the following line to WebApiConfig.cs

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

Selecting nodes with no namespace using XPath in C#

When nodes in an XML document has no prefix at all you would think that they are associated with the default namespace, but apparently this is not the case.

Those nodes are considered not associated with any namespace at all. So to select them using XPath, in the NamespaceManager first add the default namespace with any arbitrary prefix of your choosing but not string.Empty, for example:

namespaceManager.AddNameSpace(“x”, “http://…”);

Here x is just a randomly chosen prefix

Then, you can use XPath to select nodes using the prefix you just added

doc.SelectNodes(“//x:NodeName”, namespaceManager);

I spent 2 hours to figure this out, talk about wasting time.