MVVM模式应用 之xml文件的读取

时间:2023-03-09 05:25:49
MVVM模式应用 之xml文件的读取

XML如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<schools>
  <school id='1'>
    <SchoolName>郑州大学</SchoolName>
    <SchoolClass>一本</SchoolClass>
  </school>
  <school id='2'>
    <SchoolName>河南大学</SchoolName>
    <SchoolClass>一本</SchoolClass>
  </school>
  <school id='3'>
    <SchoolName>南阳理工学院</SchoolName>
    <SchoolClass>二本</SchoolClass>
  </school>
  <school id='4'>
    <SchoolName>河南工业大学 </SchoolName>
    <SchoolClass>二本</SchoolClass>
  </school>
</schools>

现在,需要把该xml文件里面的内容读取出来。

(1)首先,新建一个类University.CS,放在Model文件夹中

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace 河南大学学府.Model
{
    /// <summary>
    /// 大学类
    /// </summary>
    public class University
    {
        public int SchoolID { get; set; }
        public string  SchoolName { get; set; }
        public string SchoolClass { get; set; }
    }
}

(2)

先定义一个接口IUniversity,放在文件夹Service中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using 河南大学学府.Model;

namespace 河南大学学府.Service
{
    interface IUniversity
    {
        List<University> GetUniversityList();
    }
}

(3)

创建类UniversityService并且继承接口IUniversity

我们把读取的内容放到List<University>里面

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using 河南大学学府.Model;
using System.Xml.Linq;
using System.Linq;

namespace 河南大学学府.Service
{
    public class UniversityService:IUniversity
    {
        /// <summary>
        /// 得到河南大学列表
        /// </summary>
        /// <returns></returns>
        public List<University> GetUniversityList()
        {
            //解析文件University.xml
            XDocument doc = new XDocument();
            doc = XDocument.Load("/Data/University.xml");
            List<University> UniversityList = new List<University>();
            UniversityList = (from db in doc.Element("schools").Elements("school")
                              select
                              new University
                              {
                                  SchoolID = Int32.Parse( db.Attribute("id").Value),
                                  SchoolName = db.Element("SchoolName").Value,
                                  SchoolClass = db.Element("SchoolClass").Value
                              }).ToList();
            return UniversityList;
        }
    }
}

这样,根据University的GetUniversityList方法就能得到我们需要的数据了。