2014-09-21 1 views
0

XML을 C#으로 개체에 deserialize하려면 개체에 문자열 속성 하나와 다른 개체 목록이 있습니다. XML 객체를 설명하는 클래스가 있습니다. 코드가 작동하지 않습니다 (XML은 내 게시물의 끝에 있습니다). 내 Deserialize 코드는 아무 객체도 반환하지 않습니다.역 직렬화 된 XML을 C#의 목록을 사용하여 개체화합니다.

제가 속성에 문제가 있다고 생각합니다. 문제를 확인하고 해결하도록 조언 해 줄 수 있습니까? 도움 주셔서 감사합니다.

 var rootNode = new XmlRootAttribute(); 
     rootNode.ElementName = "createShepherdRequest"; 
     rootNode.Namespace = "http://www.sheeps.pl/webapi/1_0"; 
     rootNode.IsNullable = true; 

     Type deserializeType = typeof(Shepherd[]); 
     var serializer = new XmlSerializer(deserializeType, rootNode); 

     using (Stream xmlStream = new MemoryStream()) 
     { 
      doc.Save(xmlStream); 

      var result = serializer.Deserialize(xmlStream); 
      return result as Shepherd[]; 
     } 

[XmlRoot("shepherd")] 
public class Shepherd 
{ 
    [XmlElement("name")] 
    public string Name { get; set; } 

    [XmlArray(ElementName = "sheeps", IsNullable = true)] 
    [XmlArrayItem(ElementName = "sheep")] 
    public List<Sheep> Sheeps { get; set; } 
} 

public class Sheep 
{ 
    [XmlElement("colour")] 
    public string colour { get; set; } 
} 

C# 코드 객체에 XML을 역 직렬화 할 수 있습니다 내가

<?xml version="1.0" encoding="utf-8"?> 
<createShepherdRequest xmlns="http://www.sheeps.pl/webapi/1_0"> 
    <shepherd> 
    <name>name1</name> 
    <sheeps> 
     <sheep> 
     <colour>colour1</colour> 
     </sheep> 
     <sheep> 
     <colour>colour2</colour> 
     </sheep> 
     <sheep> 
     <colour>colour3</colour> 
     </sheep> 
    </sheeps> 
    </shepherd> 
</createShepherdRequest> 

답변

1

XmlRootAttribute 태그의 이름을 변경하지 않고 사용하는 경우 직렬화하는 XML 예제가있다 항목으로 시리얼 라이저는 <Shepherd>을 예상하지만 대신 <shepherd>을 찾습니다. (. XmlAttributeOverrides 중 하나를 배열에 작동하지 않는 것)을 해결하는 한 가지 방법을 클래스 이름 자체의 케이스를 변경하는 것입니다 :

public class shepherd 
{ 
    // ... 
} 

속성을 저글링하는 쉬운 대체하는을 만드는 것입니다 적절한 래퍼 클래스 :

[XmlRoot("createShepherdRequest", Namespace = "http://www.sheeps.pl/webapi/1_0")] 
public class CreateShepherdRequest 
{ 
    [XmlElement("shepherd")] 
    public Shepherd Shepherd { get; set; } 
}