C# XDocument.Save()不带标题

C# XDocument.Save()不带标题,c#,xml,linq-to-sql,C#,Xml,Linq To Sql,我正在使用Linq to XML编辑csproj文件,需要在不使用头的情况下保存XML 由于XDocument.Save()缺少必要的选项,那么最好的方法是什么?您可以使用xmlwriters设置来执行此操作,并将文档保存到XmlWriter: XDocument doc = new XDocument(new XElement("foo", new XAttribute("hello","world"))); XmlWriterSettings settings = new XmlW

我正在使用Linq to XML编辑csproj文件,需要在不使用
头的情况下保存XML


由于
XDocument.Save()
缺少必要的选项,那么最好的方法是什么?

您可以使用
xmlwriters设置来执行此操作,并将文档保存到
XmlWriter

XDocument doc = new XDocument(new XElement("foo",
    new XAttribute("hello","world")));

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, settings))
// or to write to a file...
//using (XmlWriter xw = XmlWriter.Create(filePath, settings))
{
    doc.Save(xw);
}
string s = sw.ToString();

一个比公认答案更简单的解决方案是使用不带标题的XML文本

例如:

// Load the file
XDocument xDocument = XDocument.Load(fileName);

// Edit the XML...

// Save the edited XML text to file
File.WriteAllText(fileName, xDocument.ToString());

我真的应该用谷歌搜索一下。我记得我想做类似的事情,并加入了一些可怕的字符串替换黑客来让它工作。很好的发现:)@MarcGravel,如何使用相同的代码显示另存为弹出窗口?