在Enum类型的XML反序列化中的问题

时间:2013-04-12 22:34:30

标签: .net c#-4.0 xml-serialization

我有一个如下所示的XML结构:

<buttons> 
  <button> 
    <text>Yes</text> 
    <type>Submit</type> 
  </button>
  <button> 
    <text>No</text> 
    <type>Cancel</type> 
  </button>
</buttons>

我有反序列化类,如下所示:

[XmlRoot("PageData")]
public class PageData
{
    [XmlArray("buttons")]
    [XmlArrayItem("button")]
    public List<Button> Buttons { get; set; }
}

public class Button
{
    [XmlElement("text")]
    public string Text { get; set; }

    [XmlElement("type"))]
    public PANELBUTTONTYPE Type { get; set; }
}


public enum PANELBUTTONTYPE
{
    [XmlEnum(Name = "Submit")]
    Submit,

    [XmlEnum(Name = "Cancel")]
    Cancel,
}

当我反序列化数据时,我收到了以下错误

{“反映属性'按钮'时出错。”}

1 个答案:

答案 0 :(得分:2)

首先,我希望如果您确实通过异常递归查看,您将找到所需的内容。错误的输出实际上非常详细。我不能以你描述的方式将它弄错,这表明你展示的例子与你的真实代码不同。但是,让我们看看问题(希望这将有助于向您展示如何解决它),使用:

string s = @"<buttons> 
  <button> 
    <text>Yes</text> 
    <type>Submit</type> 
  </button>
  <button> 
    <text>No</text> 
    <type>Cancel</type> 
  </button>
</buttons>";

try
{
    var serializer = new XmlSerializer(typeof(PageData));
    var obj = (PageData)serializer.Deserialize(new StringReader(s));
}
catch (Exception ex)
{
    while (ex != null)
    {
        Console.Error.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}

我们得到:

There is an error in XML document (1, 2).
<buttons xmlns=''> was not expected.

正确:您的xml从<buttons>开始,但您说根目录为<PageData>。我们可以解决这个问题:

[XmlRoot("buttons")]
public class PageData
{
    [XmlElement("button")]
    public List<Button> Buttons { get; set; }
}

随着改变 - 我们再试一次,它运作良好。

相关问题