2012-05-29 3 views
3

XML 문자열을 deserialize하려고했는데 객체를 deserialize하지 않습니다.XML 문자열을 역 직렬화하는 방법

내 XML 문자열은

같은
<Cars> 
    <Car> 
     <Id>123445</Id> 
     <BMW> 
      <Id>78945</Id> 
     </BMW> 
    </Car> 
</Cars> 
[Serializable()] 
[XmlRoot("Cars")] 
public class Cars 
{ 
    [XmlArrayItem("Car",typeof(Car))] 
    public Car[] Car { get; set; } 
} 

[Serializable()] 
public class Car 
{ 
    [XmlElement("Id")] 
    public long Id { get; set; } 

    [XmlArrayItem("BMW",typeof(BMW))] 
    public BMW[] BMW { get; set; } 
} 

[Serializable()] 
public class BMW 
{ 
    [XmlElement("Id")] 
    public long Id { get; set; } 
} 

보이는 그리고 이것은 내가 노력하고 코드입니다 :

string str = "xml string like above"; 
XmlSerializer ser = new XmlSerializer(typeof(Cars)); 
var wrapper = (Cars) ser.Deserialize(new StringReader(str)); 

그리고 하위 배열의 몇 내부 BMW 같은 내부 객체 않아도됩니다. 차를 직렬화하지 않습니다. 누군가 내 실수를 지적 할 수 있습니까?

[Serializable()] 
[XmlRoot("Cars")] 
public class Cars 
{ 
    [XmlElement("Car",typeof(Car))] 
    public Car[] Car { get; set; } 
} 

[Serializable()] 
public class Car 
{ 
    [XmlElement("Id")] 
    public long Id { get; set; } 

    [XmlElement("BMW",typeof(BMW))] 
    public BMW[] BMW { get; set; } 
} 
+1

XML에 데이터가없는 빈 요소가있는이 문제가 있습니까? 아니면 오류 메시지가 나타 납니까? "차를 연재하지 않는다"는 것은 무엇을 의미합니까? 직렬화 또는 직렬화에 문제가 있습니까? –

+0

오류 메시지가 무엇입니까? BMW의 정의는 어디에 있습니까? – SliverNinja

+1

@SliverNinja : 오류 메시지가 없지만 개체에 요소가 없습니다. – alice7

답변

3

XmlElement 대신 XmlArrayItem를 사용해보십시오. (Serialize 메서드는 Deserialize보다 훨씬 쉽습니다.) 잘못 배치되었거나 잘못 명명 된 특성을 강조 할 가능성이 높습니다.

2

이 XML로 예상되는 객체를 직렬화 시도하고 비교 : 항목이 더 캡슐화 태그가 없기 때문에

+0

한 가지는 객체의 모든 요소를 ​​직렬화 가능 클래스에 넣을 필요가 있습니까? – alice7

+0

각 객체는 직렬화 가능해야하지만, 각 클래스를'[Serializable]'로 꾸밀 필요는 없다고 생각합니다. – robrich

0

몇 가지 제안과 훌륭한 예제가 있습니다. 우선, 클래스 계층 구조를 이용하는 다른 클래스 구조를 제안합니다. 기본적인 자동차 프로퍼티와 메소드

  • BMW의 모든을 제공하는 클래스 - - 자동차
  • 자동차의 목록을 관리하기위한 래퍼 클래스를

    • CarList을 : 여기

      는 당신이 필요로하는 것입니다 - 특정 유형의 Car 클래스. 이 클래스는 부모 Car 클래스를 상속하며 추가 속성과 메서드를 제공합니다.

    Car 유형을 추가하려면 다른 클래스를 만들고 Car 클래스에서 상속받습니다. 코드에에

    ...

    은 여기 CarList 클래스입니다. Car 객체 목록에는 여러 개의 XmlElement 선언이 있습니다. 이것은 직렬화/역 직렬화가 다른 Car 유형을 처리하는 방법을 알고 있도록하기위한 것입니다. 더 많은 유형을 추가 할 때 유형을 설명하기 위해 여기에 행을 추가해야합니다.

    또한 직렬화/역 직렬화를 처리하는 정적 저장 및로드 메서드에 주목하십시오.

    [XmlRoot("CarList")] 
    public class CarList 
    { 
        [XmlAttribute("Name")] 
        public string Name { get; set; } 
    
        [XmlElement("Cars")] 
        [XmlElement("BWM", typeof(BMW))] 
        [XmlElement("Acura", typeof(Acura))] 
        //[XmlArrayItem("Honda", typeof(Honda))] 
        public List<Car> Cars { get; set; } 
    
        public static CarList Load(string xmlFile) 
        { 
        CarList carList = new CarList(); 
        XmlSerializer s = new XmlSerializer(typeof(CarList)); 
        TextReader r = new StreamReader(xmlFile); 
        carList = (CarList)s.Deserialize(r); 
        r.Close(); 
        return carList; 
        } 
    
        public static void Save(CarList carList, string fullFilePath) 
        { 
        XmlSerializer s = new XmlSerializer(typeof(CarList)); 
        TextWriter w = new StreamWriter(fullFilePath); 
    
        // use empty namespace to remove namespace declaration 
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 
        ns.Add("", ""); 
    
        s.Serialize(w, carList, ns); 
        w.Close(); 
        } 
    } 
    

    다음, 여기에 ...

    public class Car 
    { 
        // put properties and methods common to all car types here 
        [XmlAttribute("Id")] 
        public long Id { get; set; } 
    } 
    

    그리고 마지막으로, 특정 자동차 종류 당신의 자동차 클래스입니다 ...

    public class BMW : Car 
    { 
        // put properties and methods specific to this type here 
        [XmlAttribute("NavVendor")] 
        public string navigationSystemVendor { get; set; } 
    } 
    
    public class Acura : Car 
    { 
        // put properties and methods specific to this type here 
        [XmlAttribute("SunroofTint")] 
        public bool sunroofTint { get; set; } 
    } 
    

    이처럼 CarList를로드

    CarList carList = CarList.Load(@"C:\cars.xml"); 
    

    후, 약간의 변경을이처럼 CarList 저장 :

    : 여기

    CarList.Save(carList, @"C:\cars.xml"); 
    

    그리고하면 XML의 모습입니다

    <?xml version="1.0" encoding="utf-8"?> 
    <CarList Name="My Car List"> 
        <BWM Id="1234" NavVendor="Alpine" /> 
        <Acura Id="2345" SunroofTint="true" /> 
    </CarList> 
    

    희망을 얻는 데 도움이됩니다. 당신은 올바른 방향으로 시작했습니다!

  • 0

    내가 문제를 발견했다고 생각합니다. 나는 XML에서 다시 gettting했던 모든 속성을 포함하지 않았습니다. 속성을 잃어 버리면 직렬화 해제가 작동하지 않습니다. 그리고이 같은이 줄을 추가 :

    [XmlArray(Form = XmlSchemaForm.Unqualified), 
        XmlArrayItem("BMW", typeof(BMW), Form = XmlSchemaForm.Unqualified, IsNullable = false)] 
        public BMW[] BMWs { get; set; } 
    
    당신의 XML이 같은 경우

    : 다음

    <Cars> 
        <Car> 
        <Id>123445</Id> 
        <BMWs> 
         <BMW> 
          <Id>78945</Id> 
         <BMW> 
        </BMWs> 
        </Car> 
    </Cars> 
    

    을 그리고 그것은 일을. 이상적인 내 opbjects 생성 XSD 또는 스키마가 없었어요.

    관련 문제