您的位置:首页 > 编程语言 > C#

C# 加载Xml文件并解析

2016-07-22 16:36 423 查看
Xml文件内容大致如下:



首先新建一个wpf项目,随便往空白处添加一个按钮控件,然后在按钮的点击事件中做如下处理:

private void Load_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog onepiece = new OpenFileDialog();
onepiece.Filter = "Xml文件|*.xml";
onepiece.FileName = string.Empty;
onepiece.FilterIndex = 1;
onepiece.RestoreDirectory = true;
bool? result = onepiece.ShowDialog();
if (result == true)
{
string filename = onepiece.FileName;
XElement ccc = XDocument.Load(filename).Element("Cytq");  //寻找文件的根节点“Cytq” 并加载文件
double type = double.Parse(ccc.Element("Type").Value);    //解析文件内的元素
bool isvisiable = bool.Parse(ccc.Element("IsVisiable").Value);
XNode smallvalue = ccc.Element("Values").FirstNode;  //元素“Values”的第一个节点
//获取节点内的子元素的值
var a = from x in ccc.Descendants("MepointValue")
select new { tt = int.Parse(x.Element("Type").Value), vv = int.Parse(x.Element("Value").Value) };
foreach (var item in a)
{
int ttt = item.tt;
int vvv = item.vv;
}

MapInfoLabel.Content = string.Format(" {0} ", type);  //just for test
}
}


相关类需要引用的程序集:

using Microsoft.Win32;
using System.Windows;
using System.Xml.Linq;
using System.Linq;

这几行代码基本上能够获取Xml文件中的元素值。以上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: