2011-10-09 101 views
-1

如何将.net对象序列化为XML,然后将其反序列化?如何将对象序列化为XML

+0

http://stackoverflow.com/search?q=%5Bc%23%5D+serialize+object+xml – dtb

+0

可以通过这个链接,它可以帮助 http://stackoverflow.com/questions/4143421 /最快的方式来序列化和反序列化网络对象 –

回答

3

在VB.Net你首先一些属性添加到您的类(如果需要)

Public Class Class1 

    <XmlAttribute("value")> 
    Public Property Value As String 

    <XmlElement("name")> 
    Public Property Name As String 

End Class 

,然后使用

Dim p As New Class1() 
p.Name = "test" 
Dim sw1 = New StringWriter() 
Dim xs1 As New XmlSerializer(GetType(Class1)) 
xs1.Serialize(New XmlTextWriter(sw1), p) 
Console.WriteLine(sw1.ToString()) 
4

这是可能的使用对象和字符串扩展方法序列化。

using System.IO; 
using System.Xml.Serialization; 

namespace XmlExtensionMethods 
{ 

/// <summary> 
/// Provides extension methods useful for XML Serialization and deserialization. 
/// </summary> 
public static class XMLExtensions 
{ 
    /// <summary> 
    /// Extension method that takes objects and serialized them. 
    /// </summary> 
    /// <typeparam name="T">The type of the object to be serialized.</typeparam> 
    /// <param name="source">The object to be serialized.</param> 
    /// <returns>A string that represents the serialized XML.</returns> 
    public static string SerializeXML<T>(this T source) where T : class, new() 
    { 
     source.CheckNull("Object to be serialized."); 

     var serializer = new XmlSerializer(typeof(T)); 
     using (var writer = new StringWriter()) 
     { 
      serializer.Serialize(writer, source); 
      return writer.ToString(); 
     } 
    } 


/// <summary> 
    /// Extension method to string which attempts to deserialize XML with the same name as the source string. 
    /// </summary> 
    /// <typeparam name="T">The type which to be deserialized to.</typeparam> 
    /// <param name="XML">The source string</param> 
    /// <returns>The deserialized object, or null if unsuccessful.</returns> 
    public static T DeserializeXML<T>(this string XML) where T : class, new() 
    { 
     XML.CheckNull("XML-string"); 

     var serializer = new XmlSerializer(typeof(T)); 
     using (var reader = new StringReader(XML)) 
     { 
      try { return (T)serializer.Deserialize(reader); } 
      catch { return null; } // Could not be deserialized to this type. 
     } 
    } 
} 

} 
} 

你可以使用这样的:

string savestring; 

public void Save() 
{ 
    savestring = mySerializableObject.SerializeXML<MySerializableClass>(); 
} 

public void Load() 
{ 
    mySerializableObject = savestring.DeserializeXML<MySerializableClass>(); 
} 

PS:我不邀功这些扩展方法。

+1

伟大的答案每个人。谢谢! – jdross

0

VB.NET

Public Shared Function SerializeObj(obj As Object) As String 
    Dim xs As New System.Xml.Serialization.XmlSerializer(obj.GetType) 
    Dim w As New IO.StringWriter 
    xs.Serialize(w, obj) 
    Return w.ToString 
End Function 

让我们回到一个稍微复杂一点,你将宣布一个XML文档和提取数据出来这一点。