1

我需要创建一个可以从此 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>

我的问题是Measure,它需要是某种列表,但是当我创建一个列表时,它会错误地序列化

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

1 回答 1

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);
    }
}
于 2012-11-02T03:24:10.907 回答