定制.net xml字典(键值)序列化 [英] custom .net xml dictionary (key, value) serialization

查看:137
本文介绍了定制.net xml字典(键值)序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些类:

Class ValueSet
{
List<Value> Values { get; set; }
}

Class Value
{
String Name { get; set;}
String Value { get; set;}
}

我想像这样序列化它们: p>

and I'd like to serialize them like this:

<Values>
<name1>value1</name1>
<name2>value2</name2>
<name3>value3</name3>
</Values>

这可能吗?
谢谢!

Is this possible? Thank you!

推荐答案

回答自己的问题..

我选择了这个:

public class CustomXMLKeyValueList : IXmlSerializable
{
    public List<CustomXMLKeyValueElement> Elements { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        //ToDo-experiment with this..
        throw new NotImplementedException("This document can not be deserialized.");
    }

    public void WriteXml(XmlWriter writer)
    {
        foreach (var element in this.Elements)
        {
            element.WriteXml(writer);
        }
    }
}

public class CustomXMLKeyValueElement : IXmlSerializable
{
    public string Key { get; set; }
    public string Value { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        //ToDo-experiment with this..
        throw new NotImplementedException("This document can not be deserialized.");
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement(this.Key);
        writer.WriteString(this.Value);
        writer.WriteEndElement();
    }
}


public class KeyValueCustomXMLSerialization_Fixture
{
    public void Test()
    {
        var kvl = new CustomXMLKeyValueList() { Elements = new List<CustomXMLKeyValueElement>() };

        kvl.Elements.Add(new CustomXMLKeyValueElement() { Key = "key1", Value = "value1" });
        kvl.Elements.Add(new CustomXMLKeyValueElement() { Key = "key2", Value = "value2" });
        kvl.Elements.Add(new CustomXMLKeyValueElement() { Key = "key3", Value = "value3" });

        var xml = Serializer.SerializeToXMLString(kvl, true, true);
    }
}

这不是最好的解决方案,它,xml var包含以下美丽的字符串:

It's not the nicest of solutions but at the end of it, the xml var contains the following beautiful string:

<CustomXMLKeyValueList>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>value3</key3>
</CustomXMLKeyValueList>

'Serializer'是一个神奇的类,它像这个,而(因为'true,true')ommiting命名空间和xml声明..

The 'Serializer' is a magical class that does something like this, while (because of 'true,true') ommiting namespaces and xml declarations..

这篇关于定制.net xml字典(键值)序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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