2012-11-02 229 views
1

我需要創建一個可以從這個XML被deserialised反序列化XML

<Item> 
    <Description>Timber(dry)</Description> 
    <Measure Type="VOLUME"> 
     <Value>1.779</Value> 
     <Units>m3</Units> 
    </Measure> 
    <Measure Type="WEIGHT"> 
     <Value>925.08</Value> 
     <Units>Kilogram</Units> 
    </Measure> 
    <Measure> 
     <Value>1</Value> 
     <Units>Units</Units> 
    </Measure> 
    </Item> 

我的問題是措施一個對象,它需要某種形式的名單,但是當我創建了一個 列表它串行化錯誤

<Item> 
    <Description>Timber(dry)</Description> 
    <Measures> <--- Dont want this <Measures> tag 
    <Measure Type="VOLUME"> 
     <Value>1.779</Value> 
     <Units>m3</Units> 
    </Measure> 
    <Measure Type="WEIGHT"> 
     <Value>925.08</Value> 
     <Units>Kilogram</Units> 
    </Measure> 
    <Measure> 
     <Value>1</Value> 
     <Units>Units</Units> 
    </Measure> 
    </Measures> <--- 
    </Item> 

這是我迄今爲止

public class Item 
    { 
    public Item() 
    { 
     this.Measures = new List<Measure>(); 
    }  

    public string Description { get; set; } 

    public List<Measure> Measures { get; set; } 
    } 

    public class Measure 
    { 

    public string Value { get; set; } 

    public string Units { get; set; } 

    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string Type { get; set; } 
    } 
+0

..並通過錯誤..? –

+0

我已更新該問題。也許它會澄清更多 – Gaven

回答

3

您需要用[XmlElement]屬性修飾Measures屬性,以向序列化程序指示它需要序列化(和反序列化)爲(裸)元素,而不是將它們包裝在另一個元素中。

public class StackOverflow_13188624 
{ 
    const string XML = @" <Item> 
          <Description>Timber(dry)</Description> 
          <Measure Type=""VOLUME""> 
           <Value>1.779</Value> 
           <Units>m3</Units> 
          </Measure> 
          <Measure Type=""WEIGHT""> 
           <Value>925.08</Value> 
           <Units>Kilogram</Units> 
          </Measure> 
          <Measure> 
           <Value>1</Value> 
           <Units>Units</Units> 
          </Measure> 
          </Item>"; 

    public class Item 
    { 
     public Item() 
     { 
      this.Measures = new List<Measure>(); 
     } 

     public string Description { get; set; } 
     [System.Xml.Serialization.XmlElement(ElementName = "Measure")] 
     public List<Measure> Measures { get; set; } 
    } 

    public class Measure 
    { 
     public string Value { get; set; } 
     public string Units { get; set; } 
     [System.Xml.Serialization.XmlAttributeAttribute()] 
     public string Type { get; set; } 
    } 

    public static void Test() 
    { 
     MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML)); 
     XmlSerializer xs = new XmlSerializer(typeof(Item)); 
     Item item = (Item)xs.Deserialize(ms); 
     Console.WriteLine(item.Measures); 
    } 
} 
+0

謝謝,我到處尋找,但無法找到任何答案 – Gaven

+0

@carlosfigueira我問一個類似的問題,請你檢查它,在這裏:http://stackoverflow.com/questions/13247449/自定義的XML序列化,以全新的標籤,和屬性和根 – Saeid