【问题标题】:Unexpected node type Element意外的节点类型元素
【发布时间】:2014-10-30 13:20:27
【问题描述】:

我有以下XML:

<Envelope>
 <Body>
  <RESULT>
   <SUCCESS>TRUE</SUCCESS>
   <RecipientId>9876543210</RecipientId>
   <ORGANIZATION_ID>12345-67890-b9e6bcd68d4fb511170ab3fcff55179d</ORGANIZATION_ID>
  </RESULT>
 </Body>
</Envelope>

我试图反序列化为:

[XmlRoot(ElementName = "Envelope")]
public class Add_Recipent_response
{
    public string Body { get; set; }
    public string RESULT { get; set; }
    public string SUCCESS { get; set; }
    public string RecipientId { get; set; }
    public string ORGANIZATION_ID { get; set; }
}

用这个方法:

protected void deserializeXML(string xmlResponse)
{
    XmlSerializer deserializer = new XmlSerializer(typeof(Add_Recipent_response));
    using (TextReader reader = new StringReader(xmlResponse))
    {
        try
        {
            Add_Recipent_response XmlData = (Add_Recipent_response)deserializer.Deserialize(reader);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetBaseException());
        }
    }
}

这会引发异常:

InnerException = {"Unexpected node type Element. ReadElementString method can only be called on elements with simple or empty content. Line 4, position 2."}

谁能告诉我我做错了什么?

【问题讨论】:

标签: c# asp.net xml xml-serialization xml-deserialization


【解决方案1】:

Body 和 Result 也应该是一个类,因为它包含元素。类似的东西

[XmlRoot(ElementName = "Envelope")]
public class Add_Recipent_response
{
    public Body Body { get; set; }
}

public class Body
{
    public Result RESULT { get; set; }
}

public class Result
{
    public string SUCCESS { get; set; }
    public string RecipientId { get; set; }
    public string ORGANIZATION_ID { get; set; }
}

【讨论】:

  • 谢谢 - 我是序列化的新手。我会试一试... -EDIT- 刚试了一下,它的工作原理,非常感谢。只要允许,我就会接受。
猜你喜欢
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
相关资源
最近更新 更多