Remove Xml Declaration from Xml message

I had a requirement, in which I need to remove Xml declaration from incoming xml message. Message was being generated from external system.

Xml Declaration is of the form:
<?xml version="1.0" encoding="UTF-8"?>

Although I don’t see anything wrong in having xml declaration, but I had a requirement to remove it. After googling for some time I didn’t get any working code. Then I tried the following. Sharing here, it might be useful to some other geek.

StreamReader sr = new StreamReader("File.xml");
XmlDocument inDoc = new XmlDocument();
doc.LoadXml(sr.ReadToEnd());
sr.Close();
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlWriter xWriter = XmlWriter.Create(sb, settings);
inDoc.Save(xWriter);
xWriter.Close();
XmlDocument outDoc = new XmlDocument();
outDoc.LoadXml(sb.ToString());

Advertisements

3 Responses to Remove Xml Declaration from Xml message

  1. Sam says:

    Root element is missing. at doc.LoadXml(sr.ReadToEnd());

    • araheem says:

      Try to load a valid xml file. Usually ‘Root element is missing’ error message comes in a situation when xml file is empty.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: