| Message =输入字符串的格式不正确"反序列化xml时

时间:2015-09-25 07:33:26

标签: c# .net xml serialization

我有以下方法来反序列化XML:

公共类XMLObjects {     public static T ConvertXmlToClass(s​​tring xml)     {

    xml = "";
    xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    xml += "<root>";
    xml += "   <success>true</success>";
    xml += "   <data>";
    xml += "      <item>";
    xml += "         <Barcode>20450000817386</Barcode>";
    xml += "         <StateId>1</StateId>";
    xml += "         <WareReceiverId />";
    xml += "      </item>";
    xml += "   </data>";
    xml += "   <errors />";
    xml += "   <warnings />";
    xml += "   <info />";
    xml += "</root>";

    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "root";
    xRoot.IsNullable = true;
    var serializer = new XmlSerializer(typeof(T), xRoot);
    return (T)serializer.Deserialize(new StringReader(xml));
}

}

这是对象类:

   [Table("DocumentsTracking", Schema = "np")]
    public partial class DocumentsTracking
    {

        [Key]
        [XmlElement("Barcode")]
        public string Barcode { get; set; }
        [XmlElement("StateId")]
    public Nullable<int> StateId { get; set; }
        [XmlElement("WareReceiverId")]
        public Nullable<int> WareReceiverId { get; set; }

    }

我遇到以下异常:

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There is an error in XML document (1, 524).
  Source=System.Xml
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
       at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
       at Iwatch.Accounting.Data.XMLObjects.ConvertXmlToClass[T](String xml) in f:\proj\Iwatch.Accounting.Data\XMLObjects.cs:line 71
       at Iwatch.Accounting.Data.Logic.XmlDataLogic`1.UpdateRecords(String xml) in f:\proj\Iwatch.Accounting.Data.Logic\XmlDataLogic.cs:line 15
       at Iwatch.Accounting.Data.Logic.XmlDataLogic`1.RefreshAllByStringList(List`1 list) in f:\proj\Iwatch.Accounting.Data.Logic\XmlDataLogic.cs:line 56
       at Iwatch.Accounting.UI.MainForm.button1_Click(Object sender, EventArgs e) in f:\proj\Iwatch.Accounting.UI\MainForm.cs:line 45
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Iwatch.Accounting.UI.Program.Main() in f:\proj\Iwatch.Accounting.UI\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.FormatException
       HResult=-2146233033
       Message=Input string was not in a correct format.
       Source=mscorlib
       StackTrace:
            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.XmlSerializationReaderXmlRoot1.Read1_NullableOfInt32(Boolean checkType)
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXmlRoot1.Read13_DocumentsTracking(Boolean isNullable, Boolean checkType)
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXmlRoot1.Read14_XmlRootDataOfDocumentsTracking(Boolean isNullable, Boolean checkType)
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXmlRoot1.Read15_Item(Boolean isNullable, Boolean checkType)
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXmlRoot1.Read16_root()
       InnerException: 

如何正确设置getter和setter?或者也许还有其他方法可以解决它?我试图这样做,它正在发挥作用,但还有更好的方法吗?

[XmlIgnore]
public Nullable<int> DeliveryForm { get; set; }

[NotMapped]
[XmlElement("DeliveryForm")]
public string DeliveryFormString
{
    get
    {
        return this.DeliveryForm != null ? this.DeliveryForm.Value.ToString() : "";
    }
    set
    {

        this.DeliveryForm = (value.Equals("") ? 0 : Int32.Parse(value));
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
                //string xml = "";
                //xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                //xml += "<root>";
                //xml += "   <success>true</success>";
                //xml += "   <data>";
                //xml += "      <item>";
                //xml += "         <Barcode>20450000817386</Barcode>";
                //xml += "         <StateId>1</StateId>";
                //xml += "         <WareReceiverId />";
                //xml += "      </item>";
                //xml += "   </data>";
                //xml += "   <errors />";
                //xml += "   <warnings />";
                //xml += "   <info />";
                //xml += "</root>";

            Root root = new Root()
            {
                success = true,
                data = new Data()
                {
                    item = new Item()
                    {
                        Barcode = "20450000817386",
                        StateId = 1,
                        WareReceiverId = null 
                    },
                },
                errors = string.Empty,
                warnings = string.Empty
            };
            XmlSerializer serializer = new XmlSerializer(typeof(Root));
            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, root);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            XmlSerializer xs = new XmlSerializer(typeof(Root));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            Root  newRoot = (Root)xs.Deserialize(reader);



        }
    }
    [XmlRoot("root")]
    public partial class Root
    {

        [XmlElement("success")]
        public Boolean success { get; set; }
        [XmlElement("data")]
        public Data  data { get; set; }

        [XmlElement("errors")]
        public string errors { get; set; }
        [XmlElement("warnings")]
        public string warnings { get; set; }
    }
    [XmlRoot("data")]
    public partial class Data
    {
        [XmlElement("item")]
        public Item item { get; set; }
    }

    [XmlRoot("item")]
    public partial class Item
    {
        [XmlElement("Barcode")]
        public string Barcode { get; set; }
        [XmlElement("StateId")]
        public Nullable<int> StateId { get; set; }
        [XmlElement("WareReceiverId")]
        public int? WareReceiverId { get; set; }

    }

}
​