gpt4 book ai didi

c# - 如何有条件地以不太冗长的方式写出 XML?

转载 作者:数据小太阳 更新时间:2023-10-29 02:02:23 28 4
gpt4 key购买 nike

我想用 C# 写一个 xml 文件。这是一个像这样的基本文件:

<EmployeeConfiguration>
<Bosses>
<Boss name="BOB">
<Employees>
<Employee Id="#0001" />
<Employee Id="#0002" />
</Employees>
<Boss>
</Bosses>
</EmployeeConfiguration>

如果没有 Employee 节点,我不想有 Employees 节点...

我想使用 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 文件?

最佳答案

如果您的意思是“最快”是编写代码的最快方式(也是最简单的方式),那么创建一个自定义类并使用 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; }
}

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

// 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);

如您所见 - 在类上使用各种属性指示序列化程序应如何序列化该类。我在上面包含的一些设置实际上是默认设置,不需要明确说明 - 但我包含它们是为了向您展示它是如何完成的。

关于c# - 如何有条件地以不太冗长的方式写出 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com