用C#编写XML文件

本文关键字:文件 XML 编写 | 更新日期: 2023-09-27 18:29:54

我该怎么做:

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>

有什么建议吗?

用C#编写XML文件

我的建议是使用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);
    }
}

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

这里有一个关于如何做到这一点的好例子。如何在C#中构建XML?

如果你有任何问题,直接问。

为了让您了解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>
<employee>
   <name> Imran Khan </name>
   <nationality> Pakistani </nationality>
</employee>
XElement x = new  XElement ("employee",new XElement("name",e.name),new XElement("nationality",e.nationality) );