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打開(kāi)時(shí)有第一行的版本和編碼聲明:
<?xml version="1.0" encoding="utf-8"?>
<Persons>
? <Person id="1">
??? <Name>張三</Name>
??? <Age>18</Age>
? </Person>
</Persons>
但是有時(shí)不想保存為文件,直接獲取上面內(nèi)容為保存在一個(gè)string中:
string xml = doc.ToString();
此時(shí)xml的值為下面,獲取不到xml第一行的聲明:
<Persons>
? <Person id="1">
??? <Name>張三</Name>
??? <Age>18</Age>
? </Person>
</Persons>
解決方法有幾種:
第1種,比較簡(jiǎn)單:
第2種,寫(xiě)個(gè)擴(kuò)展方法
?
public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting){return doc.Declaration.ToString() + doc.ToString(options);}調(diào)用:
string xml = doc.ToStringWithDeclaration();?
第3種,同樣寫(xiě)個(gè)擴(kuò)展方法封裝起來(lái)
這種方法有個(gè)問(wèn)題是 生成的編碼聲明變成了encoding="utf-16",要想換成encoding="utf-8"可
寫(xiě)個(gè)類(lèi)Utf8StringWriter繼承StringWriter,并設(shè)置重載屬性Encoding為UTF8,完整代碼如下
備注:
XDocument.ToString 方法有2個(gè)重載列表,可以設(shè)置XML節(jié)點(diǎn)是否縮進(jìn)
名稱(chēng)?? ????????????????????????? ? ? ? ?? 說(shuō)明
ToString() ?? ??????????????????????? 返回此節(jié)點(diǎn)的縮進(jìn) XML。
ToString(SaveOptions) ?? ?返回此節(jié)點(diǎn)的 XML,還可以選擇禁用格式設(shè)置。
SaveOptions有兩個(gè)枚舉值:
?? DisableFormatting 不縮進(jìn)
?? None???????????????????????? 縮進(jìn)
XDocument.Save 方法也有個(gè)參數(shù)SaveOptions可以設(shè)置。
參考文章:
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
?
轉(zhuǎn)載于:https://www.cnblogs.com/suncoolcat/p/3315567.html
總結(jié)
以上是生活随笔為你收集整理的XDocument 获取包括第一行的声明(版本、编码)的所有节点的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: u盘打开是空的怎么办 如何解决U盘打开为
- 下一篇: 系统修复失败怎么办 系统修复未成功应如何