用C#编写XML文件?

时间:2012-04-02 10:55:29

标签: c# xml c#-4.0

我将如何做到这一点:

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
                     } );
}

我想要测试,例如:

Imran Khan
Pakistani

生成XML文件:

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

有什么建议吗?

5 个答案:

答案 0 :(得分:5)

我的建议是使用xml序列化:

[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);
    }
}

答案 1 :(得分:2)

有几种方法,但我喜欢的方法是使用XDocument类。

这是一个很好的例子,说明如何做到这一点。 How can I build XML in C#?

如果您有任何疑问,请询问。

答案 2 :(得分:1)

var xelement = new XElement("employee", 
   new XElement("name", employee.Name),
   new XElement("nationality", employee.Nationality),
);

xelement.Save("file.xml");

答案 3 :(得分:1)

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

XElement x = new  XElement ("employee",new XElement("name",e.name),new XElement("nationality",e.nationality) );

答案 4 :(得分:1)

为了让您了解XDocument如何根据您的循环工作,您可以这样做:

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);
}

运行后,xdoc将类似于:

<employees>
  <employee>
    <name>bob</name>
    <country>us</country>
  </employee>
  <employee>
    <name>jess</name>
    <country>us</country>
  </employee>
</employees>