XDocument 获取包括第一行的声明(版本、编码)的所有节点
XDocument保存为xml文件的方法如下:
public class Utf8StringWriter : StringWriter { public Utf8StringWriter(StringBuilder sb) : base(sb){ } public override Encoding Encoding { get { return Encoding.UTF8; } } } public static string ToStringWithDeclaration(this XDocument xdoc) { StringBuilder sb = new StringBuilder(); using (TextWriter tw = new Utf8StringWriter(sb)) { xdoc.Save(tw, SaveOptions.DisableFormatting); } return sb.ToString(); }备注:
XDocument.ToString 方法有2个重载列表,可以设置XML节点是否缩进
名称 说明ToString() 返回此节点的缩进 XML。
ToString(SaveOptions) 返回此节点的 XML,还可以选择禁用格式设置。
SaveOptions有两个枚举值:
DisableFormatting 不缩进
None 缩进
XDocument.Save 方法也有个参数SaveOptions可以设置。
参考文章:
http://msdn.microsoft.com/zh-cn/library/vstudio/bb538297%28v=vs.90%29.aspx
http://stackoverflow.com/questions/1228976/xdocument-tostring-drops-xml-encoding-tag
http://stackoverflow.com/questions/5248400/why-does-the-xdocument-give-me-a-utf16-declaration