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

时间:2021-12-25 19:37:31

Hello and thanks in advance for the help. I am having an issue when trying to deserialize an XElement into an object using an XmlSerializer and a StringReader. My code to deserialize is this:

您好,并提前感谢您的帮助。尝试使用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;
        }

I know the contents of the reader as revealed by the exception are:

我知道例外所揭示的读者内容是:

<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>

And my RegisterServerObject class looks like the following:

我的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; }

    }

And at the risk of information overload the exact exception message I am getting is this:

并且存在信息过载的风险,我得到的确切异常消息是:

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)}

It seems there is an issue with converting the value of an xml element, ParentID maybe, into an int in order to instantiate the class, but I am not sure why that would be. Thank you in advance for the help!

似乎将xml元素的值(可能是ParentID)转换为int以实例化类是一个问题,但我不确定为什么会这样。提前谢谢你的帮助!

3 个解决方案

#1


22  

The problem is that the property GroupID is declared as an integer, but its value is empty (<GroupID/>). One solution is to change the XML so that the value for that element is a valid integer:

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

<GroupID>0</GroupID>

Another solution would be to deserialize that value as a string, and convert to an integer which users of the type may consume:

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

    [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; }
    }

#2


3  

First you need to set XmlIgnore attribute for GroupID property

首先,您需要为GroupID属性设置XmlIgnore属性

[XmlRoot("Server")]
public class RegisterServerObject
{
   . . .
   [XmlIgnore]
   public int GroupID { get; set; }
   . . .
}

then you can create adapter that you will use for deserialization:

然后您可以创建将用于反序列化的适配器:

[XmlRoot("Server")]
public class RegisterServerObjectAdapter : RegisterServerObject
{
    [XmlElement("GroupID")]
    public string GroupIDNew
    {
        get { return GroupID.ToString(); }
        set
        {
            int outInt;
            int.TryParse(value, out outInt);
            GroupID = outInt;
        }
    }
}

and finaly I have modified DeserializeSingleServerFromXml method a bit

最后我有点修改了DeserializeSingleServerFromXml方法

    static RegisterServerObject DeserializeSingleServerFromXml(XDocument serverElement)
    {
        var deserializer = new XmlSerializer(typeof(RegisterServerObjectAdapter));
        return (RegisterServerObject)deserializer.Deserialize(serverElement.CreateReader(ReaderOptions.OmitDuplicateNamespaces));
    }

#3


1  

Could it be the GroupID that it's having issues with. Since no value for GroupID is provided, I believe it tries to pass it as a string.Empty which obviously wouldn't set to an int property.

可能是它遇到问题的GroupID。由于没有提供GroupID的值,我相信它会尝试将其作为string.Empty传递,显然不会将其设置为int属性。

You could try the following:

您可以尝试以下方法:

[XmlIgnore]
public int GroupID 
{
    get { !string.IsNullOrEmpty(GroupIDAsText) ? int.Parse(GroupIDAsText) : 0; }
    set { GroupID = value; }
}

[XmlAttribute("GroupID")
public int GroupIDAsText { get; set; }

.

#1


22  

The problem is that the property GroupID is declared as an integer, but its value is empty (<GroupID/>). One solution is to change the XML so that the value for that element is a valid integer:

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

<GroupID>0</GroupID>

Another solution would be to deserialize that value as a string, and convert to an integer which users of the type may consume:

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

    [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; }
    }

#2


3  

First you need to set XmlIgnore attribute for GroupID property

首先,您需要为GroupID属性设置XmlIgnore属性

[XmlRoot("Server")]
public class RegisterServerObject
{
   . . .
   [XmlIgnore]
   public int GroupID { get; set; }
   . . .
}

then you can create adapter that you will use for deserialization:

然后您可以创建将用于反序列化的适配器:

[XmlRoot("Server")]
public class RegisterServerObjectAdapter : RegisterServerObject
{
    [XmlElement("GroupID")]
    public string GroupIDNew
    {
        get { return GroupID.ToString(); }
        set
        {
            int outInt;
            int.TryParse(value, out outInt);
            GroupID = outInt;
        }
    }
}

and finaly I have modified DeserializeSingleServerFromXml method a bit

最后我有点修改了DeserializeSingleServerFromXml方法

    static RegisterServerObject DeserializeSingleServerFromXml(XDocument serverElement)
    {
        var deserializer = new XmlSerializer(typeof(RegisterServerObjectAdapter));
        return (RegisterServerObject)deserializer.Deserialize(serverElement.CreateReader(ReaderOptions.OmitDuplicateNamespaces));
    }

#3


1  

Could it be the GroupID that it's having issues with. Since no value for GroupID is provided, I believe it tries to pass it as a string.Empty which obviously wouldn't set to an int property.

可能是它遇到问题的GroupID。由于没有提供GroupID的值,我相信它会尝试将其作为string.Empty传递,显然不会将其设置为int属性。

You could try the following:

您可以尝试以下方法:

[XmlIgnore]
public int GroupID 
{
    get { !string.IsNullOrEmpty(GroupIDAsText) ? int.Parse(GroupIDAsText) : 0; }
    set { GroupID = value; }
}

[XmlAttribute("GroupID")
public int GroupIDAsText { get; set; }

.