将转换后的字典 (c#) 的节点/属性名称更改为 XML
本文关键字:属性 XML 节点 转换 字典 | 更新日期: 2023-09-27 18:30:43
我用这篇文章将我的字典转换为xml:
将字典<字符串,字符串>转换为xml的简单方法,反之亦然
我在做什么:
Dictionary<int, string> dicEntityRules = new Dictionary<int, string>();
// add the items to dicEntityRules
DataContractSerializer serializer = new DataContractSerializer(dicEntityRules.GetType());
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
serializer.WriteObject(writer, dicEntityRules);
writer.Flush();
sw.ToString();
}
}
但是,我的 xml 是这样的:
<KeyValueOfintstring>
<Key>2048</Key>
<Value>66</Value>
</KeyValueOfintstring>
我可以更改此节点/节点名称吗?
我想要一些这样的:
<Order>
<entity>2048</entity>
<rule>66</rule>
</Order>
问候。
墨菲[[|]]'s
将字典转换为List<Order>
并序列化:
void Main()
{
var dicEntityRules = new Dictionary<int, string>();
dicEntityRules.Add(1, "One");
// Convert to List<Order>
var orders = dicEntityRules.Select (er =>
new Order {entity=er.Key, rule=er.Value}).ToList();
var serializer = new DataContractSerializer(typeof(List<Order>));
using (var sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
serializer.WriteObject(writer, orders);
writer.Flush();
var s = sw.ToString();
}
}
}
[DataContract()]
public class Order
{
[DataMember]
public int entity { get; set; }
[DataMember]
public string rule { get; set; }
}