xml to linq C#实例 类和xml文件互转换

xml文件

<?xml version="1.0" encoding="utf-8" ?>
<User>
  <UserID>34e4257b-b364-4ddc-979d-bcfbb5288f5a</UserID>
  <Films>
    <Film>
      <Title>蜘蛛侠</Title>
      <ID>30</ID>
    </Film>
    <Film>
      <Title>天生一对</Title>
      <ID>65</ID>
    </Film>
    <Film>
      <Title>山楂树之恋</Title>
      <ID>130</ID>
    </Film>
  </Films>
</User>

类1

public class FavoritesInfo
   {
       public string UserID { get; set; }
 
       private List<FilmInfo> _ListFilm = new List<FilmInfo>();
       public List<FilmInfo> ListFilm
       {
           get { return _ListFilm; }
           set { _ListFilm=value;}
       }
   }
 

类2

public class FilmInfo
  {
      public string ID { get; set; }
      public string Title { get; set; }
      public string Img { get; set; }
      public string Tags { get; set; }
      //public string FlashLink { get; set; }
      public List<FlashLinkInfo> ListFlash { get; set; }
      public string CreationYear { get; set; }
      public string Scores { get; set; }
      /// <summary>
      /// 简介
      /// </summary>
      public string Intro { get; set; }
      /// <summary>
      /// 主演
      /// </summary>
      public string Author { get; set; }
      public string FlashLink { get; set; }
  }
 

读xml文件 转成类

public List<FavoritesInfo> GetFavorites()
     {
         List<FavoritesInfo> listFavorites = new List<FavoritesInfo>();
         // 读xml文件
         // string xmlFile = Server.MapPath("DvdList.xml"); //获取XML文件的路径
// XDocument doc = XDocument.Load(xmlFile);

         string strXml =  ReadXmlData();
         if (!string.IsNullOrEmpty(strXml))
         {
             byte[] bs = Encoding.UTF8.GetBytes(strXml);
             MemoryStream ms = new MemoryStream(bs);
             XDocument xdoc = XDocument.Load(ms);
 
             listFavorites = (
     from favoriteinfo in xdoc.Descendants("User")
     select new FavoritesInfo
     {
         UserID = favoriteinfo.Element("UserID").Value.Trim(),
         ListFilm = (
         from filminfo in favoriteinfo.Descendants("Film") // xdoc.Descendants("rows")
         select new FilmInfo
         {
             ID = filminfo.Element("ID").Value,
             Title = filminfo.Element("Title").Value,
         }
         ).ToList(),
 
     }
  ).ToList();
 
         }
         return listFavorites;
     }
 

C#类转成xml文件

public void SaveFavorites(FavoritesInfo favoriteInfo)
       {
           if (favoriteInfo == null) return;
 
           XElement xml = new XElement("User", new XElement("UserID", favoriteInfo.UserID),
          new XElement("Films",
              from p in favoriteInfo.ListFilm
              select new XElement("Film",
                   new XElement("Title", p.Title),
                     new XElement("ID", p.ID)
                               )
                               )
              );
// 保存xml文件 到磁盘上
           //CreatXmlData(xml.ToString());
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", ""));

doc.Add(xml); 

doc.Save(fileName);

       }
 

如果xml文件类似如下

<?xml version="1.0" encoding="utf-8" ?>
<Armys>
<Army>
  <ArmyID>12</ArmyID>
  <ArmyName>集团军A</ArmyName>
  <ArmyNameEn></ArmyNameEn>
  <BtnBG></BtnBG>
  <ElectronicExe></ElectronicExe>
  <ListMemorabilia>
    <PDFFile>
      <PDFID>fc855a91-55c6-40e9-a527-d64f106559e9</PDFID>
      <PDFFileName>《iPhone开发基础教程》.pdf</PDFFileName>
      <PDFFilePath>F:\ DownLoad\《iPhone开发基础教程》.pdf</PDFFilePath>
    </PDFFile>
    <PDFFile>
      <PDFID>c21c96bf-ae91-4aa7-8697-d8685a6a4bc6</PDFID>
      <PDFFileName>lustre2010_controlsurface_user_guide.pdf</PDFFileName>
      <PDFFilePath>F:\DownLoad\lustre2010_controlsurface_user_guide.pdf</PDFFilePath>
    </PDFFile>
  </ListMemorabilia>
  <ListMemoriesHistorical >
    <PDFFile>
      <PDFID>fc855a91-55c6-40e9-a527-d64f106559e9</PDFID>
      <PDFFileName>《iPhone开发基础教程》.pdf</PDFFileName>
      <PDFFilePath>F:\DownLoad\《iPhone开发基础教程》.pdf</PDFFilePath>
    </PDFFile>
  </ListMemoriesHistorical>
  <ListPicture />
  <ListStatisticalForms />
  
</Army>
</Armys>

则 获取数据写法

string XMLFilePath = "c:\Data\ArmyData.xml";
      public  List<ArmyInfo> LoadData()
      {
          List<ArmyInfo> list = new List<ArmyInfo>();
          var cities = from c in XElement.Load(XMLFilePath).Elements("Army") select c;
          foreach (var item in cities)
          {
              ArmyInfo cityInfo = new ArmyInfo
              {
                  ArmyID = item.Element("ArmyID").Value,
                  ArmyName = item.Element("ArmyName").Value,
                  Review = item.Element("Review") == null ? string.Empty : item.Element("Review").Value,
                  ArmyNameEn = item.Element("ArmyNameEn") == null ? string.Empty : item.Element("ArmyNameEn").Value,
                  BtnBG = item.Element("BtnBG") == null ? string.Empty : item.Element("BtnBG").Value,
                  ElectronicExe = item.Element("ElectronicExe") == null ? string.Empty : item.Element("ElectronicExe").Value,
 
                  ListMemorabilia = (
                   from pdfInfo in item.Element("ListMemorabilia").Descendants("PDFFile")
                   select new PDFFileInfo {
                       PDFFileName = pdfInfo.Element("PDFFileName") == null ? string.Empty : pdfInfo.Element("PDFFileName").Value,
                       PDFFilePath = pdfInfo.Element("PDFFilePath") == null ? string.Empty : pdfInfo.Element("PDFFilePath").Value,
                       PDFID = pdfInfo.Element("PDFID") == null ? string.Empty : pdfInfo.Element("PDFID").Value,
                   }).ToList(),
 
                  ListMemoriesHistorical = (
                 from pdfInfo in item.Element("ListMemoriesHistorical").Descendants("PDFFile")
                 select new PDFFileInfo
                 {
                     PDFFileName = pdfInfo.Element("PDFFileName") == null ? string.Empty : pdfInfo.Element("PDFFileName").Value,
                     PDFFilePath = pdfInfo.Element("PDFFilePath") == null ? string.Empty : pdfInfo.Element("PDFFilePath").Value,
                     PDFID = pdfInfo.Element("PDFID") == null ? string.Empty : pdfInfo.Element("PDFID").Value,
                 }).ToList(),
 
 
                  ListPlay = (
       from playInfo in item.Descendants("Play") // xdoc.Descendants("rows")
       select new PlayInfo
       {
           PlayID = playInfo.Element("PlayID") == null ? string.Empty : playInfo.Element("PlayID").Value,
           PlayFileName = playInfo.Element("PlayFileName") == null ? string.Empty : playInfo.Element("PlayFileName").Value,
           PlayName = playInfo.Element("PlayName") == null ? string.Empty : playInfo.Element("PlayName").Value,
       }
       ).ToList(),
                  // SectionNamePinYin = item.Element("SectionNamePinYin").Value
              };
              list.Add(cityInfo);
          }
          return list;
      }
 
原文地址:https://www.cnblogs.com/z_lb/p/2473696.html