2017-05-03 5 views
0

나는 C#에서 XmlSerializer 클래스를 사용하여 누군가로부터 당기는 XML을 deserialize하려고합니다. 불행하게도, 그들은 그들의 루트 요소는 "직원"라는 한 후 해당 루트 요소 내부의 내부 요소는 "직원"라는됩니다같은 이름의 중첩 요소가있는 XML 파일을 역 직렬화하는 방법은 요소 중 하나가 root입니까?

<Employee xmlns="http://www.testxmlns.com/employee"> 
    <Employee> 
     <OtherElement>OE</OtherElement> 
     ... 
    </Employee> 
    <Employee> 
     <OtherElement>OE</OtherElement> 
     ... 
    </Employee> 
</Employee> 

내가 아니라 정확하게 find another question that is very similar 할 수 있었다. 여기처럼 내 현재의 객체가 모습입니다 : 나는 다음을 실행하면, 모든 (예외가 발생하지) 작동하는 것 같다

[XmlType("Employee")] 
[XmlRootAttribute(Namespace = "http://www.testxmlns.com/employee", IsNullable = true)] 
public class Employee 
{ 
    [XmlElement("Employee")] 
    public Employee[] InnerEmployee; 

    [XmlElement("OtherElement")] 
    public String OtherElement; 

    ... 
} 

하지만 반환 된 개체의 모든 직원 객체의 내부 목록을 포함, 널 (null) 인 입력 한 XML에 따라 null이되어서는 안됩니다.

Employee retObj; 
XmlSerializer serializer = new XmlSerializer(typeof(Employee)); 
using (TextReader sr = new StringReader(xmlString)) 
{ 
    retObj = (Employee)serializer.Deserialize(sr); 
} 
return retObj; 

아무 도움이됩니다.

답변

1

this fiddle에서 코드를 가져 와서 실행하면 ... 작동합니다!

그러나 내가 제안하는 것은 두 개의 클래스를 갖는 것입니다 : 하나는 '루트'를위한 것이고 다른 하나는 각 자식 요소를위한 것입니다. 당신이 또한 작동 this fiddle에서 볼 수

[XmlRoot("Employee", Namespace = "http://www.testxmlns.com/employee")] 
public class EmployeeRoot 
{ 
    [XmlElement("Employee")] 
    public Employee[] Employees { get; set; } 
} 

public class Employee 
{ 
    public string OtherElement { get; set; } 
} 

:이 덜 혼란과 함께 작업 할 수있다.