假設你有以下類:
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();
}
您可以從循環到單獨的方法移動代碼,但它仍然會更難閱讀和支持。
LINQ是一種查詢語言,你不用它來構建任何東西。 – Phill
如果您正在討論使用System.Xml.Linq命名空間中的類來構建xml,那麼它不會比XmlWriter的使用更快,但它會更容易 –
我看不到您的數組如何對應於xml試圖建立。三個單獨的數組不是分層數據。您的xml表示分層數據 –