2017-04-16 26 views
0

我希望我不会重复这个问题,但我找不到能帮助我的东西。将特定的XML数据反序列化到类C#

我有以下.xml,我想反序列化到我的课程中。

<?xml version="1.0" encoding="UTF-8" ?> 
<config> 
    <buildings> 
     <building> 
      <name>Name</name> 
      <id>1</id> 
      <build_time>750</build_time> 
      <time_factor>1.2</time_factor> 
     </building> 
     <building> 
      <name>Name</name> 
      <id>2</id> 
      <build_time>150</build_time> 
      <time_factor>1.8</time_factor> 
     </building> 
     <building> 
      <name>Name</name> 
      <id>3</id> 
      <build_time>950</build_time> 
      <time_factor>1.4</time_factor> 
     </building> 
    </buildings> 
</config> 

我想从id = 2的元素中加载name,id,building_time和time_factor到以下类中。

public class Test 
{ 
    public string name { get; set; } 
    public int id { get; set; } 
    public int build_time { get; set; } 
    public double time_factor { get; set; } 
} 

什么是最好的方法来完成这项任务? 谢谢。

+0

您需要提供最低work3ed例子。你试过什么了?你有没有做过使用'XPath'来根据参数分离节点的研究? –

+1

[如何反序列化XML文档]可能的重复(http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document) – MickyD

+0

@AndrewTruckle对不起,我忘了把它包括在我的主要帖子中,我试图反序列化它,但我得到一个关于我的构造函数的错误。但是jdweng发布了一些帮助我的东西。 – gpenner

回答

0

尝试以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test2.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 

      Test test1 = doc.Descendants("building") 
       .Where(x => (int)x.Element("id") == 1) 
       .Select(x => new Test() { 
        name = (string)x.Element("name"), 
        id = (int)x.Element("id"), 
        build_time = (int)x.Element("build_time"), 
        time_factor = (double)x.Element("time_factor") 
       }).FirstOrDefault(); 
     } 
    } 
    public class Test 
    { 
     public string name { get; set; } 
     public int id { get; set; } 
     public int build_time { get; set; } 
     public double time_factor { get; set; } 
    } 
} 
+0

谢谢你,这帮了我。 – gpenner