code_junkie

De/Serialize directly To/From XML Linq

Nov 12th, 2011
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. XDocument doc = new XDocument();
  6. MyClass c = new MyClass();
  7. c.SomeValue = "bar";
  8.  
  9. doc.Add(c);
  10.  
  11. Console.Write(doc.ToString());
  12. Console.ReadLine();
  13. }
  14. }
  15.  
  16. [XmlRoot(ElementName="test")]
  17. public class MyClass
  18. {
  19. [XmlElement(ElementName = "someValue")]
  20. public string SomeValue { get; set; }
  21. }
  22.  
  23. public XDocument Serialize<T>(T source)
  24. {
  25. XDocument target = new XDocument();
  26. XmlSerializer s = new XmlSerializer(typeof(T));
  27. System.Xml.XmlWriter writer = target.CreateWriter();
  28. s.Serialize(writer, source);
  29. writer.Close();
  30. return target;
  31. }
  32.  
  33. public void Test1()
  34. {
  35. MyClass c = new MyClass() { SomeValue = "bar" };
  36. XDocument doc = Serialize<MyClass>(c);
  37. Console.WriteLine(doc.ToString());
  38. }
Add Comment
Please, Sign In to add comment