反序列化XML数组元素

时间:2011-08-11 20:41:26

标签: c#

所以,反序列化工作正常,但我有一些像这样的xml:

<File>
  <Stuff>stuff</Stuff>
  <Devices>
    <Device Type="1">
      <Number>1</Number>
    </Device>
    <Device Type="2">
      <Number>2</Number>
    </Device>
  </Devices>
</File>

当它到达设备数组时......第一个设备是唯一一个填充到对象中的设备。以下是课程:

            XmlSerializer deserializer;
            XmlRootAttribute xRoot = new XmlRootAttribute();
            FileStream stream = new FileStream(CONFIG_PATH, FileMode.Open);
            XmlReader reader = new XmlTextReader(stream);

            // Details configuration area.
            xRoot.ElementName = "File";
            xRoot.IsNullable = true;
            deserializer = new XmlSerializer(typeof(File), xRoot);
            Configuration = (File)deserializer.Deserialize(reader);

[Serializable()]
[XmlRoot(ElementName = "File", IsNullable = true)]
public sealed class File
{
    [XmlElement("Devices")]
    public Devices Devices { get; set; }
}

// <summary>
/// Configuration device elements.
/// </summary>
[Serializable()]
[XmlRoot("Devices", IsNullable = true)]
public sealed class Devices
{
    [XmlElement("Device")]
    public DeviceElements[] DeviceElements { get; set; }
}

/// <summary>
/// Configuration Devices.
/// </summary>
[Serializable()]
[XmlRoot("Device", IsNullable = true)]
public sealed class DeviceElements
{
    [XmlAttribute("Type")]
    public string DeviceType { get; set; }

    [XmlElement("Number")]
    public int DeviceNumber { get; set; }
}

同样,只有第一个Device被填充,我玩过XmlArray和XmlArrayItem,但是他们都没有给我第一个值。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

你必须在其他地方做错事。只需使用XML的Devices部分:

  <Devices>
    <Device Type="1">
      <Number>1</Number>
    </Device>
    <Device Type="2">
      <Number>2</Number>
    </Device>
  </Devices>

我能够使用您在上一个问题中使用的类似代码,为多个Devices子项成功反序列化DeviceElements个类实例,并使用与上一个问题相同的代码:

FileStream stream = new FileStream("test.xml", FileMode.Open);
XmlReader reader = new XmlTextReader(stream);

XmlSerializer deserializer = new XmlSerializer(typeof(Devices));
var devicesResult = (Devices)deserializer.Deserialize(reader);

修改

使用完整的XML:

<File>
  <Stuff>stuff</Stuff>
  <Devices>
    <Device Type="1">
      <Number>1</Number>
    </Device>
    <Device Type="2">
      <Number>2</Number>
    </Device>
  </Devices>
</File>

这为我成功反序列化:

FileStream stream = new FileStream("test.xml", FileMode.Open);
XmlReader reader = new XmlTextReader(stream);

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "File";
xRoot.IsNullable = true;

XmlSerializer deserializer = new XmlSerializer(typeof(File), xRoot);
var fileResult = (File)deserializer.Deserialize(reader);

旁注 - 您可能不应该将您的类命名为.NET框架中已有的类(System.IO.File),同样在上面的代码示例设置中,由于您使用了Xml根,因此不需要无论如何,只要留下这个名字:

FileStream stream = new FileStream("test.xml", FileMode.Open);
XmlReader reader = new XmlTextReader(stream);
XmlSerializer deserializer = new XmlSerializer(typeof(File));
var fileResult = (File)deserializer.Deserialize(reader);