假设您有以下课程:
public class Device
{
public string Software { get; set; }
public IEnumerable<Sens> Sensors { get; set; }
}
public class Sens
{
public string Name { get; set; }
public IEnumerable<Channel> Channels { get; set; }
}
public class Channel
{
public int Id { get; set; }
}
你有以下设备列表
var devices = new List<Device> {
new Device {
Software = "Windows",
Sensors = new List<Sens> {
new Sens {
Name = "Sensor1",
Channels = new List<Channel> {
new Channel { Id = 1 },
new Channel { Id = 2 }
}
},
new Sens {
Name = "Sensor2",
Channels = new List<Channel> {
new Channel { Id = 5 }
}
}
}
}
};
构建 XML 看起来像
var dlx = new XElement("dlx",
new XAttribute("vars", "1.0"),
new XAttribute("id", 133),
new XAttribute("type", "system_info"),
from d in devices
select new XElement("device",
new XAttribute("software", d.Software),
from s in d.Sensors
select new XElement("sens",
new XAttribute("name", s.Name),
from c in s.Channels
select new XElement("chan",
new XAttribute("id", c.Id)))));
dlx.Save(path_to_xml);
这会产生以下 xml:
<dlx vars="1.0" id="133" type="system_info">
<device software="Windows">
<sens name="Sensor1">
<chan id="1" />
<chan id="2" />
</sens>
<sens name="Sensor2">
<chan id="5" />
</sens>
</device>
</dlx>
与 XmlWriter 相同的代码将运行得更快,但它看起来像:
var settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("path_to_xml", settings))
{
writer.WriteStartElement("dlx");
writer.WriteAttributeString("vars", "1.0");
writer.WriteAttributeString("id", "133");
writer.WriteAttributeString("type", "system_info");
foreach (var d in devices)
{
writer.WriteStartElement("device");
writer.WriteAttributeString("software", d.Software);
foreach (var s in d.Sensors)
{
writer.WriteStartElement("sens");
writer.WriteAttributeString("name", s.Name);
foreach (var c in s.Channels)
{
writer.WriteStartElement("chan");
writer.WriteAttributeString("id", c.Id.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
您可以将代码从循环移动到单独的方法,但它仍然更难阅读和支持。