Removing XML document namespace

I had to write a helper function to remove the namespace from an XML document, and I was bewildered. My first attempt was to use RemoveAllAttributes:
 
xmlDoc.DocumentElement.RemoveAllAttributes();
string s = xmlDoc.InnerXml();
 
It didn’t work! s still contained xmlns="…". I also tried
 
xmlDoc.DocumentElement.RemoveAttribute("xmlns");
 
with the same result. I had to convert to a string and then use reqular expressions:
 
string s = xmlDoc.InnerXml;
s = System.Text.RegularExpressions.Regex.Replace(s, @"(xmlns:?[^=]*=[""][^""]*[""])", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s