2012-04-02 33 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>