C# 如何在使用LINQ创建的xml中使用ISO-8859-1编码

C# 如何在使用LINQ创建的xml中使用ISO-8859-1编码,c#,xml,linq-to-xml,xml-encoding,C#,Xml,Linq To Xml,Xml Encoding,我必须创建一个编码为 <?xml version="1.0" encoding="ISO-8859-1"?> XmlDocument doc = new XmlDocument(); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); doc.AppendChild(declaration); var nod

我必须创建一个编码为

<?xml version="1.0" encoding="ISO-8859-1"?>
        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");

目前,我正在使用LINQ创建的xml将标记作为

<?xml version="1.0" encoding="UTF-8"?>
        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");


如何仅使用LINQ执行此操作。

您应该使用
xDecration

var d = new XDocument(new XDeclaration("1.0", "ISO-8859-1", ""), new XElement("Root",
    new XElement("Child1", "data1"),
    new XElement("Child2", "data2")
 ));
        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");

您可以将
XDocument
保存到具有所需编码的
StreamWriter

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);
        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");

如果您使用的是XMLDCument,则可以按如下方式执行:

        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");

Linq是执行查询,而不是编写XML。所以,当你要求一个“只使用Linq”的方法来做这件事时,答案是:没有办法做。@MareInfinitus:我相信这个问题是关于Linq到XML的,它确实可以用来编写XML,我已经相应地更改了标记。有趣的是,这确实适用于
XDocument.Save(fileName)
如果存在
XDeclaration
,则必须推断要使用的编码。