文本格式
<?xml version="1.0" encoding="utf-8"?>
<Document>
</Document>
①文本需要一个根节点
②代码读取时如果出现迷之乱码,直接将XML用UTF-8另存
③XML手工构建时,特殊字符需要转义否则会报错(程序写入的会自动转义):
<是< >是> &是& "是" '是'
④务必注意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");