我有一些类似下面的XML
<DriveLayout>
<Drive totalSpace="16" VolumeGroup="dg01" />
<Drive totalSpace="32" VolumeGroup="dg01" />
<Drive totalSpace="64" VolumeGroup="dg02" />
<Drive totalSpace="64" VolumeGroup="dg02" />
<VolumeGroups>
<VolumeGroup VolumeGroup="dg01" storageTier="1" />
<VolumeGroup VolumeGroup="dg02" storageTier="2" />
</VolumeGroups>
</DriveLayout>
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来返回XML并将属性storageTier添加到每个单独的Drive节点.有没有办法遍历每个驱动器节点并获取VolumeGroup然后从VolumeGroup节点中的XML中获取相应的storageTier?然后,我需要将正确的storageTier注入XML驱动器节点.我正在使用C#中的System.XML.
谢谢
任何帮助将不胜感激
使用LINQ to XML可以非常简洁地完成此任务.更重要的是,它使用简单的LINQ查询和字典来提供在线性时间内运行的算法.
var storageTiers = doc.Root.Element("VolumeGroups").Elements().ToDictionary(
el => (string)el.Attribute("VolumeGroup"),
el => (string)el.Attribute("storageTier"));
foreach (var driveElement in doc.Root.Elements("Drive"))
{
driveElement.SetAttributeValue("storageTier",
storageTiers[(string)driveEl.Attribute("VolumeGroup")]);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C#3.0,那么毫无疑问这是最好的方法(除非您的XML文件非常庞大并且您需要高效率,这似乎不太可能).