2013-04-09 38 views
11

Tôi đang cố gắng deserialize cấu trúc xml này.Deserialization của xml tập tin bằng cách sử dụng XmlArray?

<?xml version="1.0"?> 
<DietPlan> 
    <Health> 
     <Fruit>Test</Fruit> 
     <Fruit>Test</Fruit> 
     <Veggie>Test</Veggie> 
     <Veggie>Test</Veggie> 
    </Health> 
</DietPlan> 

Và tôi đã cố gắng:

[Serializable] 
[XmlRoot(ElementName = "DietPlan")] 
public class TestSerialization 
{ 
    [XmlArray("Health")] 
    [XmlArrayItem("Fruit")] 
    public string[] Fruits { get; set; } 

    [XmlArray("Health")] 
    [XmlArrayItem("Veggie")] 
    public string[] Veggie { get; set; } 
} 

Nhưng điều này ném một ngoại lệ "Yếu tố XML là đã có trong phạm vi hiện tại Sử dụng XML thuộc tính để xác định một tên XML hoặc namespace cho phần tử.." Cảm ơn bạn đã ủng hộ.

Trả lời

22

Bạn cần một loại phổ biến để có thể deserialize XML của bạn, và với đó bạn có thể xác định với không gian tên [XmlElement] loại để khởi tạo tùy thuộc vào tên của phần tử, như được hiển thị bên dưới.

public class StackOverflow_15907357 
{ 
    const string XML = @"<?xml version=""1.0""?> 
         <DietPlan> 
          <Health> 
           <Fruit>Test</Fruit> 
           <Fruit>Test</Fruit> 
           <Veggie>Test</Veggie> 
           <Veggie>Test</Veggie> 
          </Health> 
         </DietPlan>"; 

    [XmlRoot(ElementName = "DietPlan")] 
    public class TestSerialization 
    { 
     [XmlArray("Health")] 
     [XmlArrayItem("Fruit", Type = typeof(Fruit))] 
     [XmlArrayItem("Veggie", Type = typeof(Veggie))] 
     public Food[] Foods { get; set; } 
    } 

    [XmlInclude(typeof(Fruit))] 
    [XmlInclude(typeof(Veggie))] 
    public class Food 
    { 
     [XmlText] 
     public string Text { get; set; } 
    } 

    public class Fruit : Food { } 
    public class Veggie : Food { } 

    public static void Test() 
    { 
     MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML)); 
     XmlSerializer xs = new XmlSerializer(typeof(TestSerialization)); 
     TestSerialization obj = (TestSerialization)xs.Deserialize(ms); 
     foreach (var food in obj.Foods) 
     { 
      Console.WriteLine("{0}: {1}", food.GetType().Name, food.Text); 
     } 
    } 
} 
+0

Cảm ơn bạn. Lưu ngày của tôi! –

Các vấn đề liên quan