3

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.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
Silver
  • 443
  • 2
  • 12
  • 33
  • Linq is to do queries, not to write XML. So, as you ask for a "Linq only" method to do it, the answer is: There is no way to do it. – Mare Infinitus Jun 10 '14 at 11:08
  • 1
    @MareInfinitus: I believe this question is about _LINQ to XML_ which indeed can be used to write XML, and I have changed the tags accordingly. – Martin Liversage Jun 10 '14 at 11:10

3 Answers3

5

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")
 ));
Uriil
  • 11,948
  • 11
  • 47
  • 68
  • 1
    Interestingly, this does indeed work with `XDocument.Save(fileName)` which must infer the encoding to use if an `XDeclaration` is present. – Martin Liversage Jun 10 '14 at 11:08
2

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);
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
1

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");
cvraman
  • 1,687
  • 1
  • 12
  • 18