使用 XElement 从自定义 XML 反序列化“字典<字符串、元<组字符串、列表<字符串>>>”

本文关键字:字符串 列表 字典 XElement 自定义 XML 反序列化 使用 | 更新日期: 2023-09-27 17:57:06

我有一个Dictionary<string, Tuple<string, List<string>>> email,我想写入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 路径并将其加载到此电子邮件类中的字典中

这是我到目前为止所拥有的:

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>

使用 XElement 从自定义 XML 反序列化“字典<字符串、元<组字符串、列表<字符串>>>”

试试这个:

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

你可以试试这种方式:

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()
                                    )
                        );
}
  • 如果path参数包含 XML 文件的路径,则应使用 XElement.Load(path) 而不是 XElement.Parse(path)
  • 使用 Tuple.Create() 构造实例Tuple通常比new Tuple()样式短