XDocument.Save() without header

2020-03-08 09:06发布

I am editing csproj files with Linq-to-XML and need to save the XML without the <?XML?> header.

As XDocument.Save() is missing the necessary option, what's the best way to do this?

1条回答
贼婆χ
2楼-- · 2020-03-08 09:24

You can do this with XmlWriterSettings, and saving the document to an 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();
查看更多
登录 后发表回答