【问题标题】:Deserialising XML based on attribute values基于属性值反序列化 XML
【发布时间】:2013-04-22 13:01:01
【问题描述】:

我有一些需要反序列化的 XML

<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 将等于“另一个值”?如果不是,那么反序列化此类属性的最佳方法是什么?

【问题讨论】:

标签: c# .net xml xml-serialization


【解决方案1】:

您可以使用 XmlAttribute 属性,但您的 xml 似乎更适合 Dictionary&lt;string,string&gt;

使用 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"]);

【讨论】:

  • 非常感谢,只需要多一点代码,但可能比任何基于复杂属性的方法更明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多