序列化列表<;元组<;字符串,字符串>>;到属性
本文关键字:字符串 lt gt 属性 元组 列表 序列化 | 更新日期: 2023-09-27 18:21:24
我想将元组列表序列化为XML属性。例如:
List<Tuple<String, String>> attributes = new List<Tuple<String, String>>();
attributes.Add(New Tuple("att1", value1"));
attributes.Add(New Tuple("att2", value2"));
它应该显示为:
<Root att1="value1" att2="value2">
</Root>
编辑:我有一个这样的类,我正在使用XmlSerializer:进行序列化
public class Root
{
List<Tuple<String, String>> attributes = new List<Tuple<String, String>>();
//other attributes and elements exist in this class
}
有简单的方法吗?
感谢
您的语法不正确,因为New
在VB中是大写的,而不是C#。
请阅读XDocument
的文档,并尝试使用这些示例。
这里有一个例子:
var attributes = new List<Tuple<string, string>>();
attributes.Add(Tuple.Create("att1", "value1"));
attributes.Add(Tuple.Create("att2", "value2"));
var document = new XDocument();
var root = new XElement("Root");
document.Add(root);
foreach(var node in attributes.Select(x => new XAttribute(x.Item1, x.Item2)))
{
root.Add(node);
}
Console.WriteLine(document); // <Root att1="value1" att2="value2" />
编辑:
要使用XmlSerializer
,请使用属性:
[XmlType("Root")]
public class Root
{
[XmlAttribute("attr1")]
public string Attribute1 { get; set; }
[XmlAttribute("attr2")]
public string Attribute2 { get; set; }
}
或者,您需要为动态属性实现IXmlSerializable
。