2017-04-16 55 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