Home  >  Article  >  php教程  >  LinqToXML~读XML文件

LinqToXML~读XML文件

WBOY
WBOYOriginal
2016-07-06 13:30:261028browse

linq的出现,带给我们的是简结,快速,可读性,它由linq to sql,linq to object,linq to xml组成,我的博客之前有对linq to sql的讲解,而今天,我将讲一个linq to xml架构,将对于操作XML文件进行读写操作,它会让你像使用linq to sql一样,操作你的xml

linq的出现,带给我们的是简结,快速,可读性,它由linq to sql,linq to object,linq to xml组成,我的博客之前有对linq to sql的讲解,而今天,我将讲一个linq to xml架构,将对于操作XML文件进行读写操作,它会让你像使用linq to sql一样,操作你的xml文件,OK,我们来看一下,下面的一个XML文件。

复制代码


  
    <__isset>
      true
      true
      true
      true
      true
      true
      false
      false
      false
    
    true
    d:\path\资料\thrift文件\thrift文件\testjava.thrift
    1297
    8C:89:A5:E1:89:3D
    1
    2014/1/26 15:32:46
    0
  
  
    <__isset>
      true
      true
      true
      true
      true
      true
      false
      false
      false
    
    true
    d:\path\资料\thrift文件\thrift文件\thrift-0.8.0.exe
    4013056
    8C:89:A5:E1:89:3D
    1
    2014/1/26 15:32:46
    0
  
  
    <__isset>
      true
      true
      true
      true
      true
      true
      false
      false
      false
    
    true
    d:\path\资料\thrift文件\thrift文件\thrift_白皮书.pdf
    441217
    8C:89:A5:E1:89:3D
    1
    2014/1/26 15:32:46
    0
  
  
    <__isset>
      true
      true
      true
      true
      true
      true
      false
      false
      false
    
    true
    d:\path\资料\thrift文件\thrift文件\thrift命令.txt
    131
    8C:89:A5:E1:89:3D
    1
    2014/1/26 15:32:46
    0
  
复制代码

这个文件是thrift自动为我们生成的,现在我们使用linq to xml来读这个文件里的内容读出来,当然你也可以使用XML反序列化的方式,将它反序列化成对象,再读出。

复制代码
  System.Console.WriteLine("Loading XML data...");
            var data =
                (from e in XElement.Load("D:\\path\\资料\\thrift文件\\thrift文件\\fileUploadLog.xml_log.xml")
                                   .Elements("DataSync")
                 select new DataSync
                 {
                     OrderNumber = Convert.ToInt32(e.Element("OrderNumber").Value),
                     IsSync = Convert.ToBoolean(e.Element("IsSync").Value),
                     FilePath = e.Element("FilePath").Value,
                     CurrentSeek = Convert.ToInt64(e.Element("CurrentSeek").Value),
                     ClientKey = e.Element("ClientKey").Value,
                     OccurTime = e.Element("OccurTime").Value,
                 }).ToList();
            data.ForEach(i => System.Console.WriteLine(i.ToString()));
复制代码

而输出的结果如下:

上面的例子中,我们的XML文件使用的是元素的方式,也可以使用属性的形式,代码只要稍作修改即可。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn