XDocument.Save() 不带标题

问题描述 投票:0回答:2

我正在使用 Linq-to-XML 编辑 csproj 文件,并且需要保存不带

<?XML?>
标头的 XML。

由于

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

c# xml linq-to-sql
2个回答
35
投票

您可以使用

XmlWriterSettings
执行此操作,并将文档保存到
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();

3
投票

比接受的答案更简单的解决方案是使用 XDocument.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());
© www.soinside.com 2019 - 2024. All rights reserved.