How to deserialize element with list of attributes in C#(如何在 C# 中使用属性列表反序列化元素)
问题描述
您好,我有以下 Xml 需要反序列化:
Hi I have the following Xml to deserialize:
<RootNode>
<Item
Name="Bill"
Age="34"
Job="Lorry Driver"
Married="Yes" />
<Item
FavouriteColour="Blue"
Age="12"
<Item
Job="Librarian"
/>
</RootNote>
当我不知道键名或会有多少属性时,如何使用属性键值对列表反序列化 Item 元素?
How can I deserialize the Item element with a list of attribute key value pairs when I dont know the key names or how many attributes there will be?
推荐答案
您可以使用 XmlAnyAttribute 属性指定任意属性将被序列化和反序列化为 XmlAttribute [] 属性或使用 XmlSerializer 时的字段.
You can use the XmlAnyAttribute attribute to specify that arbitrary attributes will be serialized and deserialized into an XmlAttribute [] property or field when using XmlSerializer.
例如,如果要将属性表示为 Dictionary,则可以定义 Item 和 RootNode类如下,使用代理 XmlAttribute[] 属性将字典与所需的 XmlAttribute 数组相互转换:
For instance, if you want to represent your attributes as a Dictionary<string, string>, you could define your Item and RootNode classes as follows, using a proxy XmlAttribute[] property to convert the dictionary from and to the required XmlAttribute array:
public class Item
{
[XmlIgnore]
public Dictionary<string, string> Attributes { get; set; }
[XmlAnyAttribute]
public XmlAttribute[] XmlAttributes
{
get
{
if (Attributes == null)
return null;
var doc = new XmlDocument();
return Attributes.Select(p => { var a = doc.CreateAttribute(p.Key); a.Value = p.Value; return a; }).ToArray();
}
set
{
if (value == null)
Attributes = null;
else
Attributes = value.ToDictionary(a => a.Name, a => a.Value);
}
}
}
public class RootNode
{
[XmlElement("Item")]
public List<Item> Items { get; set; }
}
原型小提琴.
这篇关于如何在 C# 中使用属性列表反序列化元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中使用属性列表反序列化元素
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
