在我保存XDocument的旧项目中,Save函数有7个重载,包括"字符串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:\1\email.xml");
如何将XDocument保存在磁盘中?
感谢。
答案 0 :(得分:2)
您可以像这样保存XDocument
,但需要添加一些SaveOptions
(implementation)。看看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:\1\email.xml", SaveOptions.None);
答案 1 :(得分:0)
好的,我发现了怎么做。
FileStream fileStream = new FileStream(@"C:\1\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();