net.core 中不存在 XDocument 保存字符串参数

XDocument Save String parameter doesn't exists in net.core

在我保存 XDocument 的旧项目中,保存函数有大约 7 个重载,包括 "string fileName"

现在,在我使用 Net Core 的新项目中,没有重载接受应保存文档的字符串。

我有这个:

XDocument file = new XDocument();
XElement email = new XElement("Email");
XElement recipientsXml = new XElement("Recipients");
foreach (var r in recipients)
{
   var rec = new XElement("Recipient",
       new XAttribute("To", r));
   recipientsXml.Add(rec);
}
email.Add(recipientsXml);
file.Add(email);
file.Save(@"C:\email.xml");

如何将 XDocument 保存到我的磁盘中?

谢谢。

你可以这样保存XDocument,但是你需要添加一些SaveOptions (implementation). Have a look at the Implementation of XDocument:

public void Save(string fileName, SaveOptions options)
{
    XmlWriterSettings ws = GetXmlWriterSettings(options);
    if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
    {
        try
        {
            ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
        }
        catch (ArgumentException)
        {
        }
    }

    using (XmlWriter w = XmlWriter.Create(fileName, ws))
    {
        Save(w);
    }
}

您可以使用编写器实现自己的解决方案,或者像

一样简单地调用现有方法
file.Save(@"C:\email.xml", SaveOptions.None);

好的,我找到了方法。

FileStream fileStream = new FileStream(@"C:\emails.xml");
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
XmlWriter writer = XmlWriter.Create(fileStream, settings);

XDocument file = new XDocument();
XElement email = new XElement("Email");
XElement recipientsXml = new XElement("Recipients");
foreach (var r in recipients)
{
   var rec = new XElement("Recipient",
       new XAttribute("To", r));
   recipientsXml.Add(rec);
}
email.Add(recipientsXml);
file.Add(email);
file.Save(writer);

writer.Flush();
fileStream.Flush();