3

How would I go about doing 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 want a test run of, for example:

Imran Khan
Pakistani

to generate an XML File:

<employee>
   <name> Imran Khan </name>
   <nationality> Pakistani </nationality>
</employee>

Any suggestions?

ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
  • possible duplicate of [What is the best way to build XML in C# code?](http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c-sharp-code) – TJHeuvel Apr 02 '12 at 10:59
  • Many ways to do this - serialization or direct output using custom classes or LINQ to XML (for example). – Oded Apr 02 '12 at 11:01

4 Answers4

5

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);
    }
}
Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
3

There are several ways, but the one I like is using the class XDocument.

Here's a nice example on how to do it. How can I build XML in C#?

If you have any questions, just ask.

Community
  • 1
  • 1
walther
  • 13,466
  • 5
  • 41
  • 67
2

To give you an idea of how XDocument works based on your loop, you would do this:

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 running, xdoc would be something like:

<employees>
  <employee>
    <name>bob</name>
    <country>us</country>
  </employee>
  <employee>
    <name>jess</name>
    <country>us</country>
  </employee>
</employees>
gideon
  • 19,329
  • 11
  • 72
  • 113
0
<employee>
   <name> Imran Khan </name>
   <nationality> Pakistani </nationality>
</employee>

XElement x = new  XElement ("employee",new XElement("name",e.name),new XElement("nationality",e.nationality) );
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Code only answers are rarely helpful. Please elaborate on your code and explain why and how this solves the question. – RyanNerd Dec 13 '19 at 12:20