c# - 将 xml 反序列化为对象时出错 : System. FormatException 输入字符串格式不正确

标签 c# xml silverlight xml-serialization xml-deserialization

您好,在此先感谢您的帮助。 我在尝试使用 XmlSerializer 和 StringReader 将 XElement 反序列化为对象时遇到问题。我的反序列化代码是这样的:

/*deseierialize a single RegisterServerObject instance from xml*/
        static RegisterServerObject DeserializeSingleServerFromXml(XElement serverElement)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(RegisterServerObject));
            RegisterServerObject server;
            using (var reader = new StringReader(serverElement.ToString()))
                server = (RegisterServerObject)deserializer.Deserialize(reader);

            return server;
        }

我知道异常揭示的读者内容是:

<Server>
  <ServerID>11</ServerID>
  <GroupID />
  <ParentID>15</ParentID>
  <ServerName>IAProd1</ServerName>
  <User>admin</User>
  <UID>123</UID>
  <PWD>password</PWD>
  <Domain>InputAccel</Domain>
  <Location>Left</Location>
  <AssociatedModules>
    <Module>
      <ModId>1</ModId>
      <ServerId>11</ServerId>
      <ModName>TestModA</ModName>
      <ModuleStatus>1</ModuleStatus>
    </Module>
    <Module>
      <ModId>2</ModId>
      <ServerId>11</ServerId>
      <ModName>TestModB</ModName>
      <ModuleStatus>1</ModuleStatus>
    </Module>
    <Module>
      <ModId>9</ModId>
      <ServerId>11</ServerId>
      <ModName>TestModI</ModName>
      <ModuleStatus>1</ModuleStatus>
    </Module>
    <Module>
      <ModId>10</ModId>
      <ServerId>11</ServerId>
      <ModName>TestModJ</ModName>
      <ModuleStatus>1</ModuleStatus>
    </Module>
  </AssociatedModules>
</Server>

我的 RegisterServerObject 类如下所示:

[XmlRoot("Server")]
    public class RegisterServerObject
    {
        public RegisterServerObject() { }

        public int ServerID { get; set; }

        public int GroupID { get; set; }

        public int ParentID { get; set; }

        public string ServerName { get; set; }

        public string User { get; set; }

        public int Uid { get; set; }

        public string Domain { get; set; }

        public string Location { get; set; }

        public List<RegisterModuleObject> AssociatedModules { get; set; }

    }

冒着信息过载的风险,我收到的确切异常消息是这样的:

System.InvalidOperationException: There is an error in XML document (4, 4). ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Xml.XmlConvert.ToInt32(String s)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRegisterServerObject.Read3_RegisterServerObject(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderRegisterServerObject.Read4_Server()
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, Object events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   at SL_xMonitor_Frontend_RefactorV1.Views.RegisteringNewChildWindowV2.DeserializeSingleServerFromXml(XElement serverElement)
   at SL_xMonitor_Frontend_RefactorV1.Views.RegisteringNewChildWindowV2.modXmlClient_getAssociatedModulesCompleted(Object sender, getAssociatedModulesCompletedEventArgs e)
   at SL_xMonitor_Frontend_RefactorV1.XMLServersAndModulesServiceReference.XMLTablesAndModulesServiceClient.OngetAssociatedModulesCompleted(Object state)}

为了实例化类,将 xml 元素(可能是 ParentID)的值转换为 int 似乎存在问题,但我不确定为什么会这样。预先感谢您的帮助!

最佳答案

问题是属性GroupID被声明为整数,但其值为空 ( <GroupID/> )。一种解决方案是更改 XML,使该元素的值为有效整数:

<GroupID>0</GroupID>

另一种解决方案是将该值反序列化为字符串,并转换为该类型的用户可能使用的整数:

    [XmlRoot("Server")]
    public class RegisterServerObject
    {
        public RegisterServerObject() { }

        public int ServerID { get; set; }

        [XmlIgnore]
        public int GroupID { get; set; }
        [XmlElement(ElementName = "GroupID")]
        public string GroupIDStr
        {
            get
            {
                return this.GroupID.ToString();
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    this.GroupID = 0;
                }
                else
                {
                    this.GroupID = int.Parse(value);
                }
            }
        }

        public int ParentID { get; set; }

        public string ServerName { get; set; }

        public string User { get; set; }

        public int Uid { get; set; }

        public string Domain { get; set; }

        public string Location { get; set; }

        [XmlArray(ElementName = "AssociatedModules")]
        [XmlArrayItem(ElementName = "Module")]
        public List<RegisterModuleObject> AssociatedModules { get; set; }
    }

    public class RegisterModuleObject
    {
        public int ModId { get; set; }
        public int ServerId { get; set; }
        public string ModName { get; set; }
        public int ModuleStatus { get; set; }
    }

关于c# - 将 xml 反序列化为对象时出错 : System. FormatException 输入字符串格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113014/

相关文章:

c# - 将用户控件弹出到新窗口中

c# - 在同一个 NuGet 包中为 .Net 4.7.2 和 .Net 6.0 构建?

c# - 我如何在 wp7 上的 XNA 中创建点击手势之间的延迟

silverlight - 将 ListBox 绑定(bind)到 Silverlight 中的界面属性

c# - 设计一个可以直接处理 IL 的 CPU 有什么意义吗?

C# 在 application.run() 之后执行代码

java - Spring Tool Suite 应用程序上下文 xml 错误,即使所有 bean 似乎都按预期工作

php - 从 XML 文档中查找特定节点

xml - xsd 模式可以验证编码吗? UTF-8,可能吗?

c# - WP7 如何在设备上调试飞行模式?