C# 反序列化`字典<;字符串、元组<;字符串,列表<;字符串>&燃气轮机>;`使用XElement从自定义XML
我有一封C# 反序列化`字典<;字符串、元组<;字符串,列表<;字符串>&燃气轮机>;`使用XElement从自定义XML,c#,xml,dictionary,xml-serialization,xml-deserialization,C#,Xml,Dictionary,Xml Serialization,Xml Deserialization,我有一封字典电子邮件,我想在其中写入XML(序列化)并从XML加载到字典 我得到了对XML的写入: public void WritetoXML(string path) { var xElem = new XElement( "emailAlerts", email.Select(x => new XElement("email", new XAttribute("h1", x.Key), new XAttribute("body",
字典电子邮件
,我想在其中写入XML(序列化)并从XML加载到字典
我得到了对XML的写入:
public void WritetoXML(string path) {
var xElem = new XElement(
"emailAlerts",
email.Select(x => new XElement("email", new XAttribute("h1", x.Key),
new XAttribute("body", x.Value.Item1),
new XAttribute("ids", string.Join(",", x.Value.Item2))))
);
xElem.Save(path);
}
但是我被LoadXML卡住了,它获取XML路径并将其加载到这个Email类中的字典中
这就是我到目前为止所做的:
public void LoadXML(string path) {
var xElem2 = XElement.Parse(path);
var demail = xElem2.Descendants("email").ToDictionary(x => (string)x.Attribute("h1"),
(x => (string)x.Attribute("body"),
x => (string)x.Attribute("body")));
}
背景信息我的XML应该是这样的
<emailAlerts>
<email h1='Test1' body='This is a test' ids='1,2,3,4,5,10,11,15'/>
</emailAlerts>
试试这个:
var str = @"<emailAlerts>
<email h1='Test1' body='This is a test' ids='1,2,3,4,5,10,11,15'/>
</emailAlerts>";
var xml = XElement.Parse(str);
var result = xml.Descendants("email").ToDictionary(
p => p.Attribute("h1").Value,
p => new Tuple<string, List<string>>(
p.Attribute("body").Value,
p.Attribute("ids").Value.Split(',').ToList()
)
);
var str=@”
";
var xml=XElement.Parse(str);
var result=xml.subjections(“email”).ToDictionary(
p=>p.Attribute(“h1”).值,
p=>新元组(
p、 属性(“主体”)。值,
p、 属性(“ID”).Value.Split(',').ToList()
)
);
您可以这样尝试:
public void LoadXML(string path)
{
var xElem2 = XElement.Load(path);
var demail = xElem2.Descendants("email")
.ToDictionary(
x => (string)x.Attribute("h1")
, x => Tuple.Create(
(string)x.Attribute("body")
, x.Attribute("ids").Value
.Split(',')
.ToList()
)
);
}
- 如果
参数包含XML文件的路径,则应该使用path
而不是XElement.Load(path)
李>XElement.Parse(path)
- 使用
构造Tuple.Create()
实例通常比Tuple
newtuple()样式短