2017-05-03 9 views
0

XmlSerializerクラスをC#で使用しようとしていますが、私は誰かから引き出しているXMLを逆シリアル化しています。残念ながら、彼らは彼らのルート要素は「従業員」と命名しているし、そのルート要素内の内部要素も「従業員」と命名されています同じ名前のネストされた要素を持つXMLファイルを逆シリアル化する方法は、要素の1つが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; 

    ... 
} 

が、返されたオブジェクトのすべてのEmployeeオブジェクトの内側のリストを含む、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で、私があなたのコードを取って実行すると、それが動作することがわかります!

しかし私が示唆しているのは、2つのクラスを持つことです.1つは「ルート」用で、もう1つは各子要素用です。あなたはこれも機能することを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; } 
} 

:これはあまり混乱で動作するようになるだろう。

関連する問題