1) XML is just text, so you have the possibility to build it
with StringBuilder[
^] if you like
2) You can build XML as you tried, but of course, you need to adapt the code. Copy-pasting like a full won't help. See
LinqPad[
^] sample:
private XmlNode NewEmployee(XmlDocument doc, string name, int age, string phone)
{
var e = doc.CreateElement("Employee");
var aA = doc.CreateAttribute("Age");
aA.Value = age.ToString();
var aN = doc.CreateAttribute("Name");
aN.Value = name;
var aP = doc.CreateAttribute("Phone");
aP.Value = phone;
e.Attributes.Append(aN);
e.Attributes.Append(aA);
e.Attributes.Append(aP);
return e;
}
void Main()
{
var doc = new XmlDocument();
var root = doc.CreateElement("Company");
doc.AppendChild(root);
var es = doc.CreateElement("Employees");
root.AppendChild(es);
es.AppendChild(NewEmployee(doc, "Mahesh Chand", 30, "6101233333"));
es.AppendChild(NewEmployee(doc, "Rose Garner",56, "2133428778"));
doc.DumpFormatted();
}
3) And of couse you can use serialization, and strongly typed classes. See following example:
[XmlRoot("Company")]
public class Company
{
[XmlArrayItem("Employee", typeof(Employee))]
[XmlArray("Employees")]
public List<Employee> Employees;
}
public class Employee
{
[XmlAttribute("Name")]
public string Name {get; set;}
[XmlAttribute("Age")]
public int Age {get; set;}
[XmlAttribute("Phone")]
public string Phone {get;set;}
}
void Main()
{
var c = new Company();
c.Employees = new List<Employee>()
{
new Employee() {Name = "Mahesh Chand", Age=30, Phone = "6101233333"},
new Employee() {Name = "Rose Garner", Age=56, Phone="2133428778"}
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
TextWriter w = new StringWriter();
var s = new XmlSerializer(typeof(Company));
s.Serialize(w, c, ns);
w.Flush();
w.ToString().Dump();
}