23

I am editing csproj files with Linq-to-XML and need to save the XML without the <?XML?> header.

As XDocument.Save() is missing the necessary option, what's the best way to do this?

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
laktak
  • 57,064
  • 17
  • 134
  • 164

2 Answers2

34

You can do this with XmlWriterSettings, and saving the document to an XmlWriter:

XDocument doc = new XDocument(new XElement("foo",
    new XAttribute("hello","world")));

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, settings))
// or to write to a file...
//using (XmlWriter xw = XmlWriter.Create(filePath, settings))
{
    doc.Save(xw);
}
string s = sw.ToString();
Jacob Bundgaard
  • 943
  • 11
  • 29
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

A simpler solution than the accepted answer is to use XDocument.ToString() to get the XML text without the header.

Example:

// Load the file
XDocument xDocument = XDocument.Load(fileName);

// Edit the XML...

// Save the edited XML text to file
File.WriteAllText(fileName, xDocument.ToString());
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37