2012-04-02 59 views
3

我怎么会去这样做:在C#中编写XML文件?

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> 

有什么建议?

+0

[在C#代码中构建XML的最佳方式是什么?](http://stackoverflow.com/questions/284324/what-i s-the-best-way-build-xml-in-c-sharp-code) – TJHeuvel 2012-04-02 10:59:11

+0

许多方法可以做到这一点 - 使用自定义类或LINQ to XML(例如)进行序列化或直接输出。 – Oded 2012-04-02 11:01:32

回答

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

+1,思考我在C++中使用的用于xml的第三方库,C#xml序列化看起来不可抗拒。 – ApprenticeHacker 2012-04-02 11:07:02

2

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

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

如果您有任何疑问,只需询问。

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

xelement.Save("file.xml"); 
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)); 
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>