1. 程式人生 > >UWP隨筆(三)XML

UWP隨筆(三)XML

文字格式

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

①文字需要一個根節點

②程式碼讀取時如果出現迷之亂碼,直接將XML用UTF-8另存


③XML手工構建時,特殊字元需要轉義否則會報錯(程式寫入的會自動轉義):

<是&lt;   >是&gt;   &是&amp;   "是&quot;   '是&apos;

④務必注意XML節點資料直接換行會造成TextBox無法讀取到該資料的奇葩錯誤

<node>AB</node> //這樣寫

<node>AB //而不是這樣寫
</node>

開啟XML

XmlDocument doc = new XmlDocument();
doc.Load(ApplicationData.Current.LocalFolder.Path + "\\config.xml"); //UWP只能操作指定路徑檔案

獲取根節點

XmlElement root = doc.DocumentElement;

遍歷資料

<?xml version="1.0" encoding="utf-8"?>
<Document>
<App>appname</App>
<GameList>
<Game><Name>A</Name><Market><Platform>a</Platform><Platform>b</Platform></Market></Game>
<Game><Name>B</Name><Market><Platform>c</Platform><Platform>d</Platform></Market></Game>
</GameList>
</Document>

XML節點大體如上:單節點App、父節點GameList、Market

①賦值App

root.SelectSingleNode("App").InnerText = "Hello";

②獲取Game下的Name

XmlNodeList nodes = root.SelectNodes("GameList/Game");
foreach (XmlNode node in nodes) string name = node["Name"].InnerText;

③獲取Game下的Market的Platform

XmlNodeList nodes = root.SelectNodes("GameList/Game");
foreach (XmlNode node in nodes)
{
XmlNodeList child = node.SelectNodes("Market");
foreach (XmlNode i in child) string platform = i["Platform"].InnerText;
}

④儲存XML(覆蓋即原路徑儲存)

doc.Save(ApplicationData.Current.LocalFolder.Path + "\\config.xml");