简体   繁体   English

用C#编写XML文件?

[英]Writing XML Files in C#?

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: 生成XML文件:

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

Any suggestions? 有什么建议么?

My suggestion is to use xml serialization: 我的建议是使用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);
    }
}

There are several ways, but the one I like is using the class XDocument. 有几种方法,但一个我喜欢的是使用类的XDocument。

Here's a nice example on how to do it. 这是一个很好的例子。 How can I build XML in C#? 如何在C#中构建XML?

If you have any questions, just ask. 如果你有问题,就问吧。

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

xelement.Save("file.xml");
<employee>
   <name> Imran Khan </name>
   <nationality> Pakistani </nationality>
</employee>

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

To give you an idea of how XDocument works based on your loop, you would do this: 为了让您了解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);
}

After running, xdoc would be something like: 运行后, xdoc将类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM