簡體   English   中英

使用 c# 生成 xml 文件

[英]Generate xml file using c#

我想使用 c# 中的序列化生成一個 xml 文件。 我是這種語言的新手。 所以請給個提示。

我的 xml 文件的內容為-

<Employees>
    <Employee>
      <Emp id="1", name="Ajay", salary="20000"></Emp>
      <Emp id="2", name="Vinay", salary="25000"></Emp>
      <Emp id="3", name="Jay", salary="23000"></Emp>
    </Employee>
</Employees>

定義與您預期的 xml 文本匹配的 POCO(示例如下)

public class Employees
{
    [XmlArray("Employee")]
    [XmlArrayItem(typeof(Emp), ElementName="Emp")]
    public Emp[] Emps { get; set; }
}

public class Emp
{
    [XmlAttribute("id")]
    public int Id { get; set; }
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("salary")]
    public string Salary { get; set; }
}

然后構造對象並使用 XmlSerialier 對其進行序列化

public static void SerializeXml()
{
    Employees emps = new Employees()
    {
        Emps = new Emp[]
        {
            new Emp
            {
                Id = 1,
                Name = "Ajay",
                Salary = "23000",
            }
        }
    };
    
    XmlSerializer s = new XmlSerializer(typeof(Employees));
    
    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    namespaces.Add(string.Empty, string.Empty); 
    
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = true
    };
    StringBuilder sb = new StringBuilder();
    TextWriter w = new StringWriter(sb);
    using (var writer = XmlWriter.Create(w, settings))
    {
        s.Serialize(writer, emps, namespaces);
    }       
    
    Console.WriteLine(sb.ToString());
} 

小提琴樣本https://dotnetfiddle.net/c4nMwr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM