我需要创建一个可以从这个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 :(得分:3)
您需要使用Measures
属性修饰[XmlElement]
属性,以向序列化程序指示它需要序列化(和反序列化)为(裸)元素,而不是将它们包含在另一个元素。
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);
}
}