Writing XML files in C #?
How can i do this:
for( var i = 0; i < emp; i++ )
{
Console.WriteLine("Name: ");
var name = Console.ReadLine();
Console.WriteLine("Nationality:");
var country = Console.ReadLine();
employeeList.Add( new Employee(){
Name = name,
Nationality = country
} );
}
I need a test run like:
Imran Khan
Pakistani
to create XML file:
<employee>
<name> Imran Khan </name>
<nationality> Pakistani </nationality>
</employee>
Any suggestions?
+3
source to share
5 answers
My suggestion is to use XML serialization:
[XmlRoot("employee")]
public class Employee {
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("nationality")]
public string Nationality { get; set; }
}
void Main() {
// ...
var serializer = new XmlSerializer(typeof(Employee));
var emp = new Employee { /* properties... */ };
using (var output = /* open a Stream or a StringWriter for output */) {
serializer.Serialize(output, emp);
}
}
+5
source to share
There are several ways, but the one I like uses the XDocument class.
Here's a good example of how to do this. How do I create XML in C #?
If you have any questions, just ask.
+2
source to share
To give you an idea of how the XDocument works based on your loop, you would do the following:
XDocument xdoc = new XDocument();
xdoc.Add(new XElement("employees"));
for (var i = 0; i < 3; i++)
{
Console.WriteLine("Name: ");
var name = Console.ReadLine();
Console.WriteLine("Nationality:");
var country = Console.ReadLine();
XElement el = new XElement("employee");
el.Add(new XElement("name", name), new XElement("country", country));
xdoc.Element("employees").Add(el);
}
After launch, it xdoc
will look something like this:
<employees>
<employee>
<name>bob</name>
<country>us</country>
</employee>
<employee>
<name>jess</name>
<country>us</country>
</employee>
</employees>
+1
source to share