2009-07-21 77 views
1

我有一些XML,看起來像下面在.NET中循環訪問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> 

一個我需要一種方法來回去通過XML和屬性storageTier添加到每個單獨的驅動器節點。有沒有辦法循環訪問每個驅動器節點並獲取VolumeGroup,然後從VolumeGroup節點的XML中獲取相應的storageTier?然後我需要將正確的storageTier注入到XML驅動器節點中。我使用的是C#中的System.XML。

感謝

任何幫助,將不勝感激

+1

是否有你不能在3.5使用新的XML類的理由(即的XDocument,的XElement,XAttribute) – Stephan 2009-07-21 19:28:15

+0

我做了功能要求的一個網站,它運行了2.5 – Splashlin 2009-07-21 21:44:22

回答

0

我想你需要的XPath(check this out

var doc = new XmlDocument(); 
var 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> 
"; 

doc.LoadXml(xml); 
var volumeGroups = doc.SelectNodes("/DriveLayout/VolumeGroups/VolumeGroup"); 
var storageTiers = new Dictionary<string, string>(); 
if (volumeGroups != null) 
{ 
    foreach (var volumeGroup in volumeGroups) 
    { 
     var volumeGroupElement = (XmlElement) volumeGroup; 
     storageTiers.Add(
      volumeGroupElement.Attributes["VolumeGroup"].Value, 
      volumeGroupElement.Attributes["storageTier"].Value); 
    } 
} 

var nodes = doc.SelectNodes("/DriveLayout/Drive"); 
if (nodes == null) 
{ 
    return; 
} 

foreach (XmlNode node in nodes) 
{ 
    var element = (XmlElement) node; 
    var volumeGroupAttribute = element.Attributes["VolumeGroup"]; 
    if (volumeGroupAttribute == null) 
    { 
     continue; 
    } 

    var volumeGroup = volumeGroupAttribute.Value; 

    var newStorageTier = doc.CreateAttribute("storageTier"); 
    newStorageTier.Value = storageTiers[volumeGroup]; 
    element.Attributes.Append(newStorageTier); 
} 
+2

「你要完成這個例子? 「 – 2009-07-21 19:33:53

+0

也許在我離開我的工作後,隨時可以跳入並編輯.. – BigBlondeViking 2009-07-21 19:37:46

7

使用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")]); 
} 

如果您正在使用C#3.0,那麼這無疑是去(除非你的XML文件是巨大的,你需要高效率,這似乎不太可能)的最佳方式。