首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

XDocument 获取包括首先行的声明(版本、编码)的所有节点

2013-09-11 
XDocument 获取包括第一行的声明(版本、编码)的所有节点XDocument保存为xml文件的方法如下: public class U

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

热点排行