【问题标题】:Writing XML Files in C#?用 C# 编写 XML 文件?
【发布时间】:2012-04-16 00:52:05
【问题描述】:

我该怎么做:

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 c#-4.0


【解决方案1】:

我的建议是使用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,想到我在C++中使用的xml的第三方库,C# xml序列化看起来势不可挡。
【解决方案2】:

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

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

如果你有任何问题,尽管问。

【讨论】:

    【解决方案3】:
    <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】:

    为了让您了解 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>
    

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 2012-03-09
      • 2010-10-04
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多