我想在 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>
uj5u.com熱心網友回復:
定義與您預期的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419686.html
標籤:
上一篇:在EntityFrameworkCore中記錄SQL
下一篇:我可以在不使用整個MassTransit框架的情況下使用MassTransit/Automatonymoussaga嗎?
