code_junkie

XmlSerialize a custom collection with an Attribute

Nov 13th, 2011
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using System.Collections.ObjectModel;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4.  
  5. namespace SerialiseCollection
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. var c = new MyCollection();
  12. c.Add("Hello");
  13. c.Add("Goodbye");
  14.  
  15. var serializer = new XmlSerializer(typeof(MyCollection));
  16. using (var writer = new StreamWriter("test.xml"))
  17. serializer.Serialize(writer, c);
  18. }
  19. }
  20.  
  21. [XmlRoot("MyCollection")]
  22. public class MyCollection : Collection<string>
  23. {
  24. [XmlAttribute()]
  25. public string MyAttribute { get; set; }
  26.  
  27. public MyCollection()
  28. {
  29. this.MyAttribute = "SerializeThis";
  30. }
  31. }
  32. }
  33.  
  34. <?xml version="1.0" encoding="utf-8"?>
  35. <MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  36. <string>Hello</string>
  37. <string>Goodbye</string>
  38. </MyCollection>
  39.  
  40. <MyCollection MyAttribute="SerializeThis"
  41. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  42. xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  43. <string>Hello</string>
  44. <string>Goodbye</string>
  45. </MyCollection>
  46.  
  47. [Serializable]
  48. public class MyCollectionWrapper {
  49. [XmlAttribute]
  50. public string SomeProp {get;set;} // custom props etc
  51. [XmlAttribute]
  52. public int SomeOtherProp {get;set;} // custom props etc
  53. public Collection<string> Items {get;set;} // the items
  54. }
  55.  
  56. <MyCollection MyAttribute="SerializeThis"
  57. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  58. xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  59. <Items>
  60. <string>Hello</string>
  61. <string>Goodbye</string>
  62. <Items>
  63. </MyCollection>
  64.  
  65. <MyCollection MyAttribute="SerializeThis"
  66. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  67. xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  68. <string>Hello</string>
  69. <string>Goodbye</string>
  70. </MyCollection>
Add Comment
Please, Sign In to add comment