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種,比較簡單:
第2種,寫個擴展方法
?
public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting){return doc.Declaration.ToString() + doc.ToString(options);}調用:
string xml = doc.ToStringWithDeclaration();?
第3種,同樣寫個擴展方法封裝起來
這種方法有個問題是 生成的編碼聲明變成了encoding="utf-16",要想換成encoding="utf-8"可
寫個類Utf8StringWriter繼承StringWriter,并設置重載屬性Encoding為UTF8,完整代碼如下
備注:
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 获取包括第一行的声明(版本、编码)的所有节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u盘打开是空的怎么办 如何解决U盘打开为
- 下一篇: 【iBoard电子学堂】【iCore双核