Man findet schon so einige Beispiele, die ein Object von einem WCF Service mit dem DataContractSerializer in eine XML serialisiert.
So, nun hat man das Objekt in der XML stehen aber von “Wohlgeformtheit” der XML fehlt jede Spur und will man gleich auch noch mehrere Objekte serialisieren, wirds schon etwas hakelig.
Aber gut hier mal eine Lösung die ein Array von Objekten in eine wohlgeformte XML serialisiert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #region WriteEntityCountry /// <summary> /// Handles the ReadCountryCompleted event of the client control. /// </summary> /// <param name="sender">The source of the event.</param> static void client_ReadCountryCompleted(object sender, ReadCountryCompletedEventArgs result) { try { var settings = new XmlWriterSettings { Indent = true, ConformanceLevel = ConformanceLevel.Auto }; var serializer = new DataContractSerializer(typeof(Country[])); using (XmlWriter xml = XmlWriter.Create("SerializedEntities/countries.xml", settings)) { if (xml != null) { xml.WriteStartDocument(); serializer.WriteObject(xml, result.Result.Countries); } } } catch (TargetInvocationException invocationException) { (invocationException.InnerException.Message as object).PublishEvent(PublishEventNames.Error); } } #endregion |
Und der Weg aus der XML wieder in das Objekt. In meinem Beispiel hier, deserialisiere ich das Objekt in ein Dictionary
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #region GetCountries /// <summary> /// Gets the countries. /// </summary> /// <returns></returns> public Dictionary<string, string> GetCountries() { var dictionary = new Dictionary<string, string>(); var serializer = new DataContractSerializer(typeof(Country[])); Country[] countries; using (Stream result = File.Open("SerializedEntities/countries.xml", FileMode.Open)) { countries = (Country[])serializer.ReadObject(result); } foreach (var country in countries) { dictionary.Add(country.ID.ToString(), country.Land); } return dictionary; } #endregion |
Viel Spaß beim entwickeln : )







