首页 > 解决方案 > 如何获取具有值的xml标签和C#中的智能值?

问题描述

在下面的 xml 中,我想获取 drive0 和 drive1。

<Config>
 <Name>AAAA</Name>
 <drive0>C:/Temp</drive0>
 <drive1>//192.168.1.1/Test</drive1>
 <drive2></drive2>
</Config>

我写了以下代码,但这并不聪明。我不迷恋linq。

String configPath = "config.xml";
XElement loadedConfig = XElement.Load(configPath);

IEnumerable<String> infos = from item in loadedConfig.Elements("drive0")
                                        select item.Value;
IEnumerable<String> infos = from item in loadedConfig.Elements("drive1")
                                        select item.Value;
IEnumerable<String> infos = from item in loadedConfig.Elements("drive2")
                                        select item.Value;

我根据答案更改了下面的代码。

var DrivePaths = new Dictionary<string, string>()
for (int i =0; i < 3; i++)
{
   string DrivePathNum = "studyDrivePath_" + i.ToString();
   string DrivePath = loadedConfig.Descendants(DrivePathNum).FirstOrDefault()?.Value;
   studyDrivePaths.Add(DrivePathNum, sDrivePath);
}

标签: c#xml

解决方案


请尝试以下方法。

C#

void Main()
{
    const string configPath = "e:\temp\config.xml";
    XDocument loadedConfig = XDocument.Load(configPath);

    string drive0 = loadedConfig.Descendants("drive0").FirstOrDefault()?.Value;
    string drive1 = loadedConfig.Descendants("drive1").FirstOrDefault()?.Value;
}

推荐阅读