简体   繁体   English

如何获取具有值和 C# 中的值的 xml 标记以实现智能?

[英]How to get xml tag which has value and the value in C# for smart?

In the following xml, I'd like to get drive0 and drive1.在下面的 xml 中,我想获取 drive0 和 drive1。

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

I wrote the following codes but this is not smart.我写了以下代码,但这并不聪明。 I am not obsessed with linq.我并不痴迷于 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;

I changed the code below based on the answer.我根据答案更改了下面的代码。

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);
}

Please try the following.请尝试以下操作。

c# 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM