反序列化XML嵌套项

时间:2016-05-18 20:41:29

标签: c# xml serialization

您好我正在尝试获取每个选项的值,如下所示。

<Mailbox>
  <Menus>
    <Specs>
      <Section>Message</Section>
        <Options>
          <Option>&amp;New</Option>
          <Option>&amp;Inbox</Option>
          <Option>&amp;Outbox</Option>
          <Option>&amp;Sent Items</Option>
          <Option>S&amp;ettings</Option>
        </Options>
    </Specs>
  </Menus>
</Mailbox>

但是当我运行下面的代码时:

[XmlRoot("Mailbox")]
public class Mailbox
{
    [XmlArray(ElementName = "Menus"), XmlArrayItem("Specs")]
    public Specs[] Menus { get; set; }
}

[XmlRoot("Specs")]
public class Specs
{
    [XmlElement("Section")]
    public string Section { get; set; }
    [XmlArray(ElementName = "Options"), XmlArrayItem("Option")]
    public Options[] OptionsList { get; set; }
}

[XmlRoot("Options")]
public class Options
{
    [XmlElement("Option")]
    public string Option { get; set; }
}

var deserializer = new XmlSerializer(typeof(Mailbox));
var textReader = new StreamReader(filename);
try
{
      var storage = (Mailbox)deserializer.Deserialize(textReader);
      for (int i = 0; i < storage.Menus.Length; i++)
      {
           MainMenu.Section = storage.Menus[i].Section;
           MainMenu.Options.Add(storage.Menus[i].Options[i]);
      }
}
catch (Exception e)
{
      MessageBox.Show(e.Message);
}
textReader.Close();

我没有得到选择;他们都只是出来了。选项列表没有正确显示,我也不知道为什么。

感谢。

2 个答案:

答案 0 :(得分:1)

您的问题是您的类型指定的<Option>元素级别太多:

[XmlArray(ElementName = "Options"), XmlArrayItem("Option")]
public Options[] OptionsList { get; set; }

表示数组的XML应具有带有内部元素<Options>的外部容器元素<Option>。但是,您的Options类型为其值指定了一个额外的嵌套<Option>元素:

[XmlRoot("Options")]
public class Options
{
    [XmlElement("Option")] // <-- This introduces an additional nested <Option> element.
    public string Option { get; set; }
}

为此,您的XML需要如下所示:

    <Options>
      <Option>
        <Option>&amp;New</Option>
      </Option>
    </Options>

它没有。

您可以使用[XmlText]标记Options.Option来消除此额外级别的嵌套:

[XmlRoot("Options")]
public class Options
{
    [XmlText]
    public string Option { get; set; }
}

答案 1 :(得分:0)

您好,根据您的xml文件,您的可序列化类将在下面

[XmlRoot(ElementName = "Options")]
public class Options
{
    [XmlElement(ElementName = "Option")]
    public List<string> Option { get; set; }
}

[XmlRoot(ElementName = "Specs")]
public class Specs
{
    [XmlElement(ElementName = "Section")]
    public string Section { get; set; }
    [XmlElement(ElementName = "Options")]
    public Options Options { get; set; }
}

[XmlRoot(ElementName = "Menus")]
public class Menus
{
    [XmlElement(ElementName = "Specs")]
    public Specs Specs { get; set; }
}

[XmlRoot(ElementName = "Mailbox")]
public class Mailbox
{
    [XmlElement(ElementName = "Menus")]
    public Menus Menus { get; set; }
}