2017-12-17 34 views
0

는 내가 달성하고자하는 것은 같은 XML 출력입니다. 나는 자동차 모델을 사용하여 사전에이 데이터를 읽는 달성 할 수있는 다음 코드의 일부 :XML 직렬화/역 직렬화 사용하여 모델

public Dictionary<int, ModelCar> Car { get; } 

    public Cars() 
    { 

     Car = new Dictionary<int, ModelCar>(); 

     foreach (var File in Directory.GetFiles(Folder, "*.xml", SearchOption.TopDirectoryOnly)) 
     { 

      ModelCar item = new ModelCar().DeserializeFile(File); 

      Car.Add(item.Id, item); 

     } 

    } 

이 문제는 결합 된 XML 출력/입력에 대한 모든 차량 데이터를 보유 사전 '자동차'를 쓰고있다. 모델 '자동차'가 어떻게 보이고 호출해야하는지에 대한 모든 힌트/학습서/예제?

편집 : 지금이 게시물에 보면 - https://stackoverflow.com/a/19600156/8333405

+0

가능한 복제 ([C#을이 같은 유형의 자식 노드를 가지고있는 XML을 역 직렬화 방법] https://stackoverflow.com/question/47765992/deserialize-xml-in-c-sharp-having-child-nodes-same-type) –

답변

0

먼저, 다음과 같이 적절한 종료 태그를 위해 XML을 수정해야는 :

다음
<?xml version="1.0" encoding="utf-8" ?> 
<cars> 
    <car id="0"> 
    <Type>1</Type> 
    <Class>Buick</Class> 
    </car> 
    <car id="1"> 
    <Type>1</Type> 
    <Class>B</Class> 
    </car> 
</cars> 

당신은 비주얼 스튜디오를하도록 할 수는 모델을 생성 너를 위해서.

  1. 당신에게 XML 파일 내용을 복사하십시오.

  2. Visual Studio 메뉴에서 편집 -> 선택하여 붙여 넣기 -> XML을 클래스로 붙여 넣기.

이제 Visual Studio에서 모델을 생성했습니다. 그들에게이 코드를 사용 사용하려면 :

// you do not need a dictionary. A List will do it. 
List<carsCar> allCars = new List<carsCar>(); 

string folder = @"G:\Projects\StackOverFlow\WpfApp2"; 

foreach (var file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly)) 
{ 
    FileStream reader = File.OpenRead(file); 
    XmlSerializer ser = new XmlSerializer(typeof(cars)); 
    cars cars = (cars)ser.Deserialize(reader); 

    allCars.AddRange(cars.car); 
} 

// if you want the car with id = 0 
var car_0 = allCars.FirstOrDefault(c => c.id == 0); 
0

시도는 XML Linq에를 사용하여 다음을

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      Cars cars = new Cars(); 
      XElement xCars = cars.Serialize(); 
     } 
    } 
    public class Cars 
    { 
     public Dictionary<int, ModelCar> Car { get; set; } 


     public Cars() 
     { 

      Car = new Dictionary<int, ModelCar>() { 
       {0, new ModelCar() { _class = "B", _type = 1, id = 0}}, 
       {1, new ModelCar() { _class = "B", _type = 1, id = 1}} 
      }; 
     } 
     public XElement Serialize() 
     { 
      return new XElement("cars", Car.AsEnumerable().Select(x => new XElement("car", new object[] { 
       new XAttribute("id", x.Key), 
       new XElement("Type", x.Value._type), 
       new XElement("Class", x.Value._class) 
      }))); 
     } 
    } 
    public class ModelCar 
    { 
     public int id { get; set; } 
     public int _type { get; set; } 
     public string _class { get;set; } 
    } 
}