C# 加載Xml文件並解析


Xml文件內容大致如下:

首先新建一個wpf項目,隨便往空白處添加一個按鈕控件,然后在按鈕的點擊事件中做如下處理:

 1 private void Load_Click(object sender, RoutedEventArgs e)
 2         {
 3             OpenFileDialog onepiece = new OpenFileDialog();
 4             onepiece.Filter = "Xml文件|*.xml";
 5             onepiece.FileName = string.Empty;
 6             onepiece.FilterIndex = 1;
 7             onepiece.RestoreDirectory = true;
 8             bool? result = onepiece.ShowDialog();
 9             if (result == true)
10             {
11                 string filename = onepiece.FileName;
12                 XElement ccc = XDocument.Load(filename).Element("Cytq");  //尋找文件的根節點“Cytq” 並加載文件
13                 double type = double.Parse(ccc.Element("Type").Value);    //解析文件內的元素
14                 bool isvisiable = bool.Parse(ccc.Element("IsVisiable").Value);
15                 XNode smallvalue = ccc.Element("Values").FirstNode;  //元素“Values”的第一個節點
16                 //獲取節點內的子元素的值
17                 var a = from x in ccc.Descendants("MepointValue")
18                         select new { tt = int.Parse(x.Element("Type").Value), vv = int.Parse(x.Element("Value").Value) };
19                 foreach (var item in a)
20                 {
21                     int ttt = item.tt;
22                     int vvv = item.vv;
23                 }
24 
25                 MapInfoLabel.Content = string.Format(" {0} ", type);  //just for test
26             }
27         }

相關類需要引用的程序集:

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

這幾行代碼基本上能夠獲取Xml文件中的元素值。以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM