通过XML循环在.NET中? [英] Looping through XML in .NET?

查看:134
本文介绍了通过XML循环在.NET中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些XML,看起来像下面

I have some XML that looks something like the one below

<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得到cooresponding storageTier出在VolumeGroup节点XML的?然后,我需要注入正确的storageTier到XML驱动节点。我使用的是C#中了System.XML。

I need a way to go back through the XML and add the attribute storageTier to each individual Drive node. Is there a way to loop through each drive node and grab the VolumeGroup then get the cooresponding storageTier out of the XML in the VolumeGroup node? I then need to inject the correct storageTier back into the XML drive node. I'm using the System.XML that's in C#.

感谢

任何帮助将不胜感激

推荐答案

我想你需要的XPath(的看看这个

I think you need 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);
}

这篇关于通过XML循环在.NET中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆