我怎么能以一种不那么冗长的方式有条件地写出XML呢?

Flo*_*ian 4 c# xml linq-to-xml

我想用C#编写一个xml文件.这是一个基本文件:

<EmployeeConfiguration>
  <Bosses>
    <Boss name="BOB">
      <Employees>
        <Employee Id="#0001" />
        <Employee Id="#0002" />
      </Employees>
    <Boss>
  </Bosses>
</EmployeeConfiguration>
Run Code Online (Sandbox Code Playgroud)

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();
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

是否有另一种(和最快的)方法来编写这种xml文件?

Rob*_*ine 6

如果你的意思是"最快"作为编写一些代码的最快方法(也是最简单的),那么创建一个自定义类并使用XmlSerializer对它进行序列化就是要走的路......

按如下方式创建类:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用这个序列化这些:

// 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);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的 - 使用类上的各种属性指示序列化程序如何序列化类.我上面包含的一些实际上是默认设置,并没有明确需要说明 - 但我已经包含它们来向您展示它是如何完成的.