我想用C#编写一个xml文件。这是一个基本文件:
<EmployeeConfiguration>
<Bosses>
<Boss name="BOB">
<Employees>
<Employee Id="#0001" />
<Employee Id="#0002" />
</Employees>
<Boss>
</Bosses>
</EmployeeConfiguration>
如果没有Employees
节点,我不希望有Employee
节点......
我想使用XElement,但我不能因为那样......所以我使用了XmlWriter。它工作正常,但我发现编写XML非常冗长:
EmployeeConfiguration config = EmployeeConfiguration.GetConfiguration();
using (XmlWriter writer = XmlWriter.Create(_fileUri, settings))
{
writer.WriteStartDocument();
// <EmployeeConfiguration>
writer.WriteStartElement("EmployeeConfiguration");
if (config.Bosses.Count > 0)
{
// <Bosses>
writer.WriteStartElement("Bosses");
foreach (Boss b in config.Bosses)
{
// Boss
writer.WriteStartElement("Boss");
writer.WriteStartAttribute("name");
writer.WriteString(b.Name);
writer.WriteEndAttribute();
if (b.Employees.Count > 0)
{
writer.WriteStartElement("Employees");
foreach (Employee emp in b.Employees)
{
writer.WriteStartElement(Employee);
writer.WriteStartAttribute(Id);
writer.WriteString(emp.Id);
writer.WriteEndAttribute();
writer.WriteEndElement();
}
}
}
}
}
是否有另一种(也是最快的)方法来编写这种xml文件?
答案 0 :(得分:6)
如果你的意思是“最快”作为编写一些代码的最快方式(也是最简单的),那么创建一个自定义类并使用XmlSerializer对其进行序列化是最佳选择... < / p>
按如下方式创建课程:
[XmlRoot("EmployeeConfiguration")]
public class EmployeeConfiguration
{
[XmlArray("Bosses")]
[XmlArrayItem("Boss")]
public List<Boss> Bosses { get; set; }
}
public class Boss
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlArray("Employees")]
[XmlArrayItem("Employee")]
public List<Employee> Employees { get; set; }
}
public class Employee
{
[XmlAttribute]
public string Id { get; set; }
}
然后你可以用这个序列化这些:
// create a serializer for the root type above
var serializer = new XmlSerializer(typeof (EmployeeConfiguration));
// by default, the serializer will write out the "xsi" and "xsd" namespaces to any output.
// you don't want these, so this will inhibit it.
var namespaces = new XmlSerializerNamespaces(new [] { new XmlQualifiedName("", "") });
// serialize to stream or writer
serializer.Serialize(outputStreamOrWriter, config, namespaces);
正如您所看到的 - 使用类上的各种属性指示序列化程序如何序列化类。我上面提到的一些实际上是默认设置,并没有明确需要说明 - 但我已经将它们包含在内以向您展示它是如何完成的。
答案 1 :(得分:1)
您可能希望使用XmlElement,XmlAttribute(等等)属性来查看XML序列化。我认为这可以为您提供所需的控制级别,以及一个非常快速,安全且易于维护的调用来进行XML转换。
答案 2 :(得分:1)
var xml = new XElement("EmployeeConfiguration",
new XElement("Bosses"),
new XElement("Boss", new XAttribute("name", "BOB"),
new XElement("Employees"),
new XElement("Employee", new XAttribute("Id", "#0001")),
new XElement("Employee", new XAttribute("Id", "#0001"))
)
);