This is my code i have,
its for a windows form
XmlDocument doc = new XmlDocument();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("C:\\Temp\\mybikes.xml",settings);
writer.WriteStartDocument();
writer.WriteStartElement("Bike");
foreach (string item in listBikes.Items)
{
string encodedXml = item.Replace(""", " ");
writer.WriteStartElement("Make");
writer.WriteStartElement("Model");
writer.WriteStartElement("Size");
writer.WriteStartElement("Year");
writer.WriteStartElement("Cost");
writer.WriteAttributeString("Bike", encodedXml);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
// Save the document to a file and auto-indent the output.
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(listBikes.GetType());
Manoj BhoirPosted Apr 13, 2015, 1:05 AM
Hi, you have not mentioned what problem exactly you are facing. There are many ways to create xml from serialize object. Please see test example for your requirement.
using System;
arrayBike = new List();
(T xmlObject)
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace XMLDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List
var bike1 = new bike();
bike1.Make = "Honda";
bike1.Model = "CBR";
bike1.Year = 2011;
bike1.Capacity = 1000;
arrayBike.Add(bike1);
var bike2 = new bike();
bike2.Make = "Yamaha";
bike2.Model = "YZ";
bike2.Year = 2009;
bike2.Capacity = 900;
arrayBike.Add(bike2);
textBox1.Text = GetXml(arrayBike);
}
public string GetXml
{
var serializer = new XmlSerializer(typeof(T));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, xmlObject);
utf8 = writer.ToString();
}
return utf8.ToString();
}
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
}
public class bike
{
private string _make;
private string _model;
private int _year;
private int _capacity;
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public int Capacity { get; set; }
}
}
Please find attached source code of above sample.
I hope this will help you :)