c# - 如何获取具有值的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#
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;
}
推荐阅读
- regex - RegEx 可与 kotlin 一起使用,但无法与 dart 一起使用
- regex - 如何只在模式中使用一次输入?
- typescript - 错误 TS2345:类型参数 '{ cluster: string; 加密:布尔值;}' 不可分配给“选项”类型的参数
- typescript - 找不到模块“vuetify/lib/framework”的声明文件
- python - python中的fillpoly属性有问题
- python - 为什么函数在嵌套函数中的 else 语句之后不返回?
- python - 有没有其他方法可以使用多个参数写入文件?
- javascript - 我在 forloop 中重置的变量没有改变
- javascript - 带有 React Hooks 的动态状态
- python - 无法安装“mediapipe”库