使用XElement

时间:2015-06-19 20:15:57

标签: c# xml dictionary xml-serialization xml-deserialization

我有一个Dictionary<string, Tuple<string, List<string>>> email,我想写入XML(Serialize),并从XML加载到Dictionary。

我这样写了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>

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

您可以尝试这种方式:

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()样式
  • 更短