【发布时间】:2020-02-22 18:45:24
【问题描述】:
我有一个 xml 类型:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<set1>
<a>
<value>False</value>
<defaultValue>False</defaultValue>
</a>
<b>
<value>False</value>
<defaultValue>False</defaultValue>
</b>
</set1>
<set2>
<c>
<value>False</value>
<defaultValue>False</defaultValue>
</c>
</set2>
</root>
现在我尝试使用以下代码将其转换为字典:
using System.Collections.Generic;
using System.Xml.Linq;
namespace testxml
{
struct ConfigFileElements
{
public string value;
public string defaultValue;
}
class xmltestread
{
public static Dictionary<string, Dictionary<string, ConfigFileElements>>
ReadConfigXml(XDocument configFile)
{
var dict = new Dictionary<string, Dictionary<string, ConfigFileElements>>();
if (configFile.Root != null)
{
foreach (var element in configFile.Root.Elements())
{
var list = new Dictionary<string, ConfigFileElements>();
foreach (var child in element.Elements())
{
var elementvalues = new ConfigFileElements();
foreach (var node in child.Elements())
{
if (node.Name.ToString().Equals("value"))
{
elementvalues.value = node.Value;
}
else if (node.Name.ToString().Equals("defaultValue"))
{
elementvalues.defaultValue = node.Value;
}
}
list.Add(child.Name.ToString(), elementvalues);
}
dict.Add(element.Name.ToString(), list);
}
}
return dict;
}
}
}
这里的问题是我必须迭代三个循环来构建我的字典,.net 中是否还有其他功能可以使代码清晰且看起来不错。
如 linq to xml 或 xml 中的任何其他类型的内置库,用于执行此类复杂操作
我还会添加更多标签,例如最小/最大值,这些标签会在现有条件中添加一些其他 if else 语句,这是另一个约束。
【问题讨论】:
标签: c# xml dictionary linq-to-xml