Xml Deserialisierung schlägt fehl

  • C#
  • .NET (FX) 4.5–4.8

Es gibt 3 Antworten in diesem Thema. Der letzte Beitrag () ist von Radinator.

    Xml Deserialisierung schlägt fehl

    Servus!

    Ich hab ein kleines Problemchen, und zwar: Wenn ich aus einem ViewModel per XmlSerializer eine *.xml Datei generiere und die anschließend in meiner (per Xamarin unter VS 2015 CE erstellten) App auslese, dann funktioniert alles, wie es sollte. Wenn ich hingegen die Datei in der gleichen App, die ich unter WPF mit .NET FW 4.5 geschrieben habe, wieder deserialiseren will, dann schlägt das Fehl. Mit der Fehlermeldung, dass der erste Knoten (in dem Fall <ArrayOfXXX> - wobei xxx mein benutzerdeinierter Typ ist) nicht erwartet wird.

    Hier mal der Code zum Serialisieren:

    C#-Quellcode

    1. internal static bool SerializeIt<T>(T obj, string filePath)
    2. {
    3. bool result = false;
    4. try
    5. {
    6. if (File.Exists(filePath))
    7. File.Delete(filePath);
    8. XmlSerializer serializer = new XmlSerializer(obj.GetType());
    9. using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
    10. {
    11. serializer.Serialize(fs, obj);
    12. }
    13. }
    14. catch (Exception ex)
    15. {
    16. result = false;
    17. Debug.WriteLine(ex);
    18. }
    19. return result;
    20. }


    Deserialisieren:

    C#-Quellcode

    1. internal static T DeserializeIt<T>(string filePath)
    2. {
    3. T result;
    4. XmlSerializer serializer = new XmlSerializer(typeof(T));
    5. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    6. {
    7. result = (T)serializer.Deserialize(fs);
    8. }
    9. return result;
    10. }


    In der App:

    C#-Quellcode

    1. public static Collection<Kunde> GibKudenListe()
    2. {
    3. string xml = ReadFile("settings.xml");
    4. var kundenListe = FromXml<Collection<Kunde>>(xml);
    5. return kundenListe;
    6. }

    und

    C#-Quellcode

    1. internal static T FromXml<T>(string xml)
    2. {
    3. T result;
    4. XmlSerializer serializer = new XmlSerializer(typeof(T));
    5. byte[] data = Encoding.UTF8.GetBytes(xml);
    6. using (MemoryStream ms = new MemoryStream(data))
    7. {
    8. result = (T)serializer.Deserialize(ms);
    9. }
    10. return result;
    11. }


    Hier mal der StackTrace:
    Spoiler anzeigen

    Quellcode

    1. System.InvalidOperationException wurde nicht behandelt.
    2. HResult=-2146233079
    3. Message=Fehler im XML-Dokument (2,2).
    4. Source=System.Xml
    5. StackTrace:
    6. bei System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
    7. bei System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
    8. bei TaskCreator.DataService.DeserializeIt[T](String filePath) in C:\Users\Rechner\Desktop\TaskCreator\TaskCreator\DataService.cs:Zeile 42.
    9. bei TaskCreator.MainWindow.btnKundenLaden_Click(Object sender, RoutedEventArgs e) in C:\Users\Rechner\Desktop\TaskCreator\TaskCreator\MainWindow.xaml.cs:Zeile 195.
    10. bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
    11. bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
    12. bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
    13. bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
    14. bei System.Windows.Controls.Primitives.ButtonBase.OnClick()
    15. bei System.Windows.Controls.Button.OnClick()
    16. bei System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
    17. bei System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
    18. bei System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
    19. bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
    20. bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
    21. bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
    22. bei System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
    23. bei System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
    24. bei System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
    25. bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
    26. bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
    27. bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
    28. bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
    29. bei System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
    30. bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
    31. bei System.Windows.Input.InputManager.ProcessStagingArea()
    32. bei System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
    33. bei System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
    34. bei System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
    35. bei System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
    36. bei System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
    37. bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
    38. bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
    39. bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
    40. bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
    41. bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
    42. bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
    43. bei MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
    44. bei System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
    45. bei System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
    46. bei System.Windows.Application.RunDispatcher(Object ignore)
    47. bei System.Windows.Application.RunInternal(Window window)
    48. bei System.Windows.Application.Run(Window window)
    49. bei TaskCreator.App.Main()
    50. bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    51. bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    52. bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    53. bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    54. bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    55. bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    56. bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    57. bei System.Threading.ThreadHelper.ThreadStart()
    58. InnerException:
    59. HResult=-2146233079
    60. Message=<ArrayOfKunde xmlns=''> wurde nicht erwartet.
    61. Source=Microsoft.GeneratedCode
    62. StackTrace:
    63. bei Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderKunde.Read5_Kunde()
    64. InnerException:


    Und zu Guter Letzt, auch noch die XML:
    Spoiler anzeigen

    XML-Quellcode

    1. <?xml version="1.0"?>
    2. <ArrayOfKunde xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    3. <Kunde>
    4. <ID>1</ID>
    5. <Name>Name</Name>
    6. <Adresse>Adresse</Adresse>
    7. <Telefon>Telefon</Telefon>
    8. <Email>Email</Email>
    9. <Auftraege>
    10. <Auftrag>
    11. <ID>0</ID>
    12. <Name>Name</Name>
    13. <Adresse>Adresse</Adresse>
    14. <Telefon>Telefon</Telefon>
    15. <Email>Email</Email>
    16. <Titel>Titel</Titel>
    17. <Text>Text</Text>
    18. <WartungsAnweisungen>
    19. <WartungsAnweisung>
    20. <ID>0</ID>
    21. <Titel>Titel</Titel>
    22. <AnweisungsText>Anweisung</AnweisungsText>
    23. <Zustaende>
    24. <string>1</string>
    25. <string>2</string>
    26. <string>3</string>
    27. </Zustaende>
    28. <DefaultZustand>4</DefaultZustand>
    29. <FotoNowendig>false</FotoNowendig>
    30. <Bemerkung />
    31. <Abgeschlossen>false</Abgeschlossen>
    32. </WartungsAnweisung>
    33. </WartungsAnweisungen>
    34. <Fertig>false</Fertig>
    35. </Auftrag>
    36. </Auftraege>
    37. </Kunde>
    38. </ArrayOfKunde>

    Hab schon auf StackOverflow gesucht, da hab ich zwar ne Lösung gefunden, nur bekomm ich dann nur den Root-Knoten (jaaa, ich weiß...super Deusch ;D).

    Wäre super, wenn mir wer helfen könnte :D
    Lg Radinator
    In general (across programming languages), a pointer is a number that represents a physical location in memory. A nullpointer is (almost always) one that points to 0, and is widely recognized as "not pointing to anything". Since systems have different amounts of supported memory, it doesn't always take the same number of bytes to hold that number, so we call a "native size integer" one that can hold a pointer on any particular system. - Sam Harwell
    @Radinator Funktioniert Serialisierung und Deserialisierung beides unter FW 4.5?
    Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
    Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
    Ein guter .NET-Snippetkonverter (der ist verfügbar).
    Programmierfragen über PN / Konversation werden ignoriert!
    Bei der Android-App ist als FW 4.5 eingestellt, für das Serialisierungs-Projekt (WPF) wird ebenfalls FW 4.5 verwendet
    In general (across programming languages), a pointer is a number that represents a physical location in memory. A nullpointer is (almost always) one that points to 0, and is widely recognized as "not pointing to anything". Since systems have different amounts of supported memory, it doesn't always take the same number of bytes to hold that number, so we call a "native size integer" one that can hold a pointer on any particular system. - Sam Harwell
    #push
    In general (across programming languages), a pointer is a number that represents a physical location in memory. A nullpointer is (almost always) one that points to 0, and is widely recognized as "not pointing to anything". Since systems have different amounts of supported memory, it doesn't always take the same number of bytes to hold that number, so we call a "native size integer" one that can hold a pointer on any particular system. - Sam Harwell