基于属性值反序列化 XML [英] Deserialising XML based on attribute values

查看:33
本文介绍了基于属性值反序列化 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 XML 需要反序列化

I have some XML that I need to deserialise

<element>
  <childElement key="myKey1">a value</childElement>
  <childElement key="myKey2">another value</childElement>
</element>

进入一个类

[XmlRoot(ElementName="element")]
public class Element
{
  public string MyKey1 { get; set; }
  public string MyKey2 { get; set; }
}

我是否可以注释 MyKey1 和 MyKey2,以便如果上面的 xml 被反序列化,那么 MyKey1 将是一个值"而 MyKey2 将等于另一个值"?如果不是,那么反序列化这样的属性的最佳方法是什么?

Is it possible for me to annotate MyKey1 and MyKey2 so that if the xml above is deserialised then MyKey1 will be "a value" and MyKey2 will equal "another value"? If not then what is the best approach to deserialising attributes like this?

推荐答案

您可以使用 XmlAttribute 属性,但您的 xml 似乎更适合 Dictionary

You can use XmlAttribute attribute but your xml seems better to fit to a Dictionary<string,string>

使用 Linq 转 Xml

Using Linq To Xml

string xml = @"<element>
    <childElement key=""myKey1"">a value</childElement>
    <childElement key=""myKey2"">another value</childElement>
</element>";

var xDoc = XDocument.Parse(xml);
var dict = xDoc.Descendants("childElement")
               .ToDictionary(x => x.Attribute("key").Value, x => x.Value);

Console.WriteLine(dict["myKey1"]);

这篇关于基于属性值反序列化 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆