Advertisement
akass

Serialize to XML

Jul 19th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. You will need wrapper classes:
  2.  
  3. public class SomeIntInfo
  4. {
  5.     [XmlAttribute]
  6.     public int Value { get; set; }
  7. }
  8.  
  9. public class SomeStringInfo
  10. {
  11.     [XmlAttribute]
  12.     public string Value { get; set; }
  13. }
  14.  
  15. public class SomeModel
  16. {
  17.     [XmlElement("SomeStringElementName")]
  18.     public SomeStringInfo SomeString { get; set; }
  19.  
  20.     [XmlElement("SomeInfoElementName")]
  21.     public SomeIntInfo SomeInfo { get; set; }
  22. }
  23. or a more generic approach if you prefer:
  24.  
  25. public class SomeInfo<T>
  26. {
  27.     [XmlAttribute]
  28.     public T Value { get; set; }
  29. }
  30.  
  31. public class SomeModel
  32. {
  33.     [XmlElement("SomeStringElementName")]
  34.     public SomeInfo<string> SomeString { get; set; }
  35.  
  36.     [XmlElement("SomeInfoElementName")]
  37.     public SomeInfo<int> SomeInfo { get; set; }
  38. }
  39. And then:
  40.  
  41. class Program
  42. {
  43.     static void Main()
  44.     {
  45.         var model = new SomeModel
  46.         {
  47.             SomeString = new SomeInfo<string> { Value = "testData" },
  48.             SomeInfo = new SomeInfo<int> { Value = 5 }
  49.         };
  50.         var serializer = new XmlSerializer(model.GetType());
  51.         serializer.Serialize(Console.Out, model);
  52.     }
  53. }
  54. will produce:
  55.  
  56. <?xml version="1.0" encoding="ibm850"?>
  57. <SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  58.   <SomeStringElementName Value="testData" />
  59.   <SomeInfoElementName Value="5" />
  60. </SomeModel>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement