1 using System;
2 using System. Collections. Generic;
3 using System. Linq;
4 using System. Web;
5 using System. Web. UI;
6 using System. Web. UI. WebControls;
7 using System. IO;
8 using System. Xml. Serialization;
9
10
11 public partial class SimplySerialization: System. Web. UI. Page
12 {
13 protected void Page_Load (object sender, EventArgs e)
14 {
15 string xmlFilePath = @ "C: \ Data \ Category. xml ";
16 Category categoryObj = new Category ();
17 categoryObj. CategoryID = 1;
18 categoryObj. CategoryName = "beer ";
19 categoryObj. Description = "soft drinks, coffee, tea, beer and liquor ";
20
21 // rename CategoryID as ID and add it as attribute
22 XmlAttributeAttribute categoryIDAttribute = new XmlAttributeAttribute ();
23 categoryIDAttribute. AttributeName = "ID ";
24 XmlAttributes attributesIdCol = new XmlAttributes ();
25 attributesIdCol. XmlAttribute = categoryIDAttribute;
26 XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides ();
27 attrOverrides. Add (typeof (Category), "CategoryID", attributesIdCol );
28
29 // rename CategoryName to Name and add it to element
30 XmlElementAttribute categoryNameElement = new XmlElementAttribute ();
31 categoryNameElement. ElementName = "Name ";
32 XmlAttributes attributesNameCol = new XmlAttributes ();
33 attributesNameCol. XmlElements. Add (categoryNameElement );
34 attrOverrides. Add (typeof (Category), "CategoryName", attributesNameCol );
35
36 XmlSerializer serializer = new XmlSerializer (typeof (Category), attrOverrides );
37 TextWriter writer = new StreamWriter (xmlFilePath );
38 serializer. Serialize (writer, categoryObj );
39 writer. Close ();
40 Response. Write ("file written successfully! ");
41
42}
43}
44
Output XML document results
1 <? Xml version = "1.0" encoding = "UTF-8"?>
2 <Category xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" ID = "1">
3 <Name> beer </Name>
4 <Description> soft drinks, coffee, tea, beer and liquor </Description>
5 </Category>