Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit the xml declarations when using XElement.Save?

XElement.Save actually does what I need but it starts the file with:

<?xml version="1.0" encoding="utf-8"?>

Is there a way to prevent this?

Should I save using other types, methods after I finish creating my XElement?

Or should I be skipping that line via XmlReader.Read? Because doing this I feel like it's more fragile as I am assuming the first line is always gonna be this xml declaration.

What's the simpliest way to accomplish this?

like image 610
Joan Venge Avatar asked Feb 25 '11 23:02

Joan Venge


3 Answers

XElement.ToString() won't add the XML declaration to the output. But I don't understand why XmlReader - or any XML parser - would have trouble with a standard XML declaration.

like image 51
Joel Mueller Avatar answered Nov 08 '22 05:11

Joel Mueller


This example writes the example xmlTree data to text file data.xml without a declaration line, yet includes indentation formatting:

XElement xmlTree = new XElement("Root",
  new XAttribute("Attribute1", 1),
  new XElement("Child1", 1),
  new XElement("Child2", 2)
);
using (var writer = XmlWriter.Create("data.xml", new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }))
  xmlTree.Save(writer);
like image 38
dapi Avatar answered Nov 08 '22 04:11

dapi


Using an XmlWriter will give you this ability.

Microsoft article: Serializing with an XML Declaration describes how to control whether serialization generates an XML declaration.

like image 38
John Arlen Avatar answered Nov 08 '22 04:11

John Arlen