日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/10/12 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 XDocument 获取包括第一行的声明(版本、编码)的所有节点 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

XDocument保存為xml文件的方法如下:

XDocument doc = new XDocument(new XDeclaration("1.0","UTF-8",null),new XElement("Persons", new XElement("Person",new XAttribute("id","1"),new XElement("Name","張三"),new XElement("Age",18)) )); doc.Save("person.xml");

person.xml打開時有第一行的版本和編碼聲明:

<?xml version="1.0" encoding="utf-8"?>

<Persons>
? <Person id="1">
??? <Name>張三</Name>
??? <Age>18</Age>
? </Person>
</Persons>


但是有時不想保存為文件,直接獲取上面內容為保存在一個string中:
string xml = doc.ToString();

此時xml的值為下面,獲取不到xml第一行的聲明:
<Persons>
? <Person id="1">
??? <Name>張三</Name>
??? <Age>18</Age>
? </Person>
</Persons>



解決方法有幾種:

第1種,比較簡單:

string xml = doc.Declaration.ToString() + doc.ToString();


第2種,寫個擴展方法

?

public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting){return doc.Declaration.ToString() + doc.ToString(options);}

調用:

string xml = doc.ToStringWithDeclaration();

?

第3種,同樣寫個擴展方法封裝起來

public static string ToStringWithDeclaration(this XDocument doc){StringBuilder sb = new StringBuilder();using (TextWriter tw = new StringWriter(sb)){ doc.Save(tw, SaveOptions.DisableFormatting);} return sb.ToString();}


這種方法有個問題是 生成的編碼聲明變成了encoding="utf-16",要想換成encoding="utf-8"可
寫個類Utf8StringWriter繼承StringWriter,并設置重載屬性Encoding為UTF8,完整代碼如下

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

?

轉載于:https://www.cnblogs.com/suncoolcat/p/3315567.html

總結

以上是生活随笔為你收集整理的XDocument 获取包括第一行的声明(版本、编码)的所有节点的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。