how to give encoding as ISO-8859-1 in xml created using LINQ

5.9k Views Asked by At

I have to create an xml file which has encoding as

<?xml version="1.0" encoding="ISO-8859-1"?>

Currently the xml I am creating using LINQ is having tag as

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

how can I do this using LINQ only.

3

There are 3 best solutions below

1
On BEST ANSWER

You should use XDeclaration:

var d = new XDocument(new XDeclaration("1.0", "ISO-8859-1", ""), new XElement("Root",
    new XElement("Child1", "data1"),
    new XElement("Child2", "data2")
 ));
0
On

You can save the XDocument to a StreamWriter having the desired encoding:

var xDocument = new XDocument(new XElement("root"));
var encoding = Encoding.GetEncoding("iso-8859-1");
using (var fileStream = File.Create("... file name ..."))
  using (var streamWriter = new StreamWriter(fileStream, encoding))
    xDocument.Save(streamWriter);
0
On

If you are using XMLDcoument, then you can do so like below:

        XmlDocument doc = new XmlDocument();
        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
        doc.AppendChild(declaration);
        var node = doc.CreateNode(XmlNodeType.Element, "Root", "");
        doc.AppendChild(node);
        doc.Save("TestDoc.xml");