2013-04-09 86 views
11

我想反序列化這個xml結構。使用XmlArray反序列化xml文件?

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

而且我想:

[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; } 
} 

但是,這將引發異常「的XML元素已經出現在當前範圍內使用XML屬性來指定元素的另一個XML名稱或名稱空間。」 謝謝你。

回答

22

您需要一個能夠反序列化XML的通用類型,並且您可以使用該名稱空間定義要根據元素的名稱實例化的類型,如下所示。

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

謝謝。拯救了我的一天! – 2013-04-10 07:30:06