Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C“将列表的KeyValuePair反序列化为”;“价值”;领域_C#_.net_C# 4.0 - Fatal编程技术网

C# C“将列表的KeyValuePair反序列化为”;“价值”;领域

C# C“将列表的KeyValuePair反序列化为”;“价值”;领域,c#,.net,c#-4.0,C#,.net,C# 4.0,我有一个用XML序列化的KeyValuePair对象,每个键都有一个值列表,如下所示: <WritableKeyValuePairOfKeyContraenteArrayOfAddress> <key> <KeyContaente>123456</KeyContaente> </key> <value> <Address>Maple road 12</Address

我有一个用XML序列化的KeyValuePair对象,每个键都有一个值列表,如下所示:

<WritableKeyValuePairOfKeyContraenteArrayOfAddress>
   <key>
      <KeyContaente>123456</KeyContaente>
   </key>
   <value>
      <Address>Maple road 12</Address>
   </value>
   <value>
      <Address>Oak street 71</Address>
   </value>
</WritableKeyValuePairOfKeyContraenteArrayOfAddress>

123456
枫树道12号
橡树街71号
问题是:当我反序列化时,对象的值只包含一个元素:第一个(“Maple road 12”)。为什么会发生这种情况

编辑: 序列化:

public static string Serializza<T>(T objectToSerialize)
    {
        using (MemoryStream memStm = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memStm, objectToSerialize);

            memStm.Seek(0, SeekOrigin.Begin);

            using (var streamReader = new StreamReader(memStm))
            {
                string result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    private static T Deserializza<T>(string xmlString)
    {
        if (xmlString.Length > 0)
        {
            try
            {
                var serializer = new DataContractSerializer(typeof(T));
                using (System.IO.MemoryStream memStm = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString)))
                {
                    return (T)serializer.ReadObject(memStm);
                }
            }
            catch
            {
                return default(T);
            }
        }
        else
            return default(T);
    }
[Serializable, StructLayout(LayoutKind.Sequential)]
public class WritableKeyValuePair<TKey, TValue> : IWritableKeyValuePair
{
    private TKey key;
    private TValue value;

    public WritableKeyValuePair() { }
    public WritableKeyValuePair(TKey key, TValue value)
    {
        this.key = key;
        this.value = value;
    }

    public override string ToString()
    {
        return WKVPUtils<TKey, TValue>.ToString(key, value);
    }

    ////[XmlProcessDeep()]
    public TValue Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public TKey Key
    {
        get { return this.key; }
        set { this.key = value; }
    }

    internal static class WKVPUtils<TKey, TValue>
    {
        public static string ToString(TKey Key, TValue Value)
        {
            StringBuilder builder1 = new StringBuilder();
            builder1.Append('[');
            if (Key != null)
                builder1.Append(Key.ToString());
            builder1.Append(", ");
            if (Value != null)
                builder1.Append(Value.ToString());
            builder1.Append(']');
            return builder1.ToString();
        }
    }
}
public静态字符串Serializza(T objectToSerialize)
{
使用(MemoryStream memStm=new MemoryStream())
{
var serializer=新的DataContractSerializer(typeof(T));
WriteObject(memStm,objectToSerialize);
memStm.Seek(0,SeekOrigin.Begin);
使用(var streamReader=newstreamreader(memStm))
{
字符串结果=streamReader.ReadToEnd();
返回结果;
}
}
}
反序列化:

public static string Serializza<T>(T objectToSerialize)
    {
        using (MemoryStream memStm = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memStm, objectToSerialize);

            memStm.Seek(0, SeekOrigin.Begin);

            using (var streamReader = new StreamReader(memStm))
            {
                string result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    private static T Deserializza<T>(string xmlString)
    {
        if (xmlString.Length > 0)
        {
            try
            {
                var serializer = new DataContractSerializer(typeof(T));
                using (System.IO.MemoryStream memStm = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString)))
                {
                    return (T)serializer.ReadObject(memStm);
                }
            }
            catch
            {
                return default(T);
            }
        }
        else
            return default(T);
    }
[Serializable, StructLayout(LayoutKind.Sequential)]
public class WritableKeyValuePair<TKey, TValue> : IWritableKeyValuePair
{
    private TKey key;
    private TValue value;

    public WritableKeyValuePair() { }
    public WritableKeyValuePair(TKey key, TValue value)
    {
        this.key = key;
        this.value = value;
    }

    public override string ToString()
    {
        return WKVPUtils<TKey, TValue>.ToString(key, value);
    }

    ////[XmlProcessDeep()]
    public TValue Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public TKey Key
    {
        get { return this.key; }
        set { this.key = value; }
    }

    internal static class WKVPUtils<TKey, TValue>
    {
        public static string ToString(TKey Key, TValue Value)
        {
            StringBuilder builder1 = new StringBuilder();
            builder1.Append('[');
            if (Key != null)
                builder1.Append(Key.ToString());
            builder1.Append(", ");
            if (Value != null)
                builder1.Append(Value.ToString());
            builder1.Append(']');
            return builder1.ToString();
        }
    }
}
private static T反序列化(字符串xmlString)
{
如果(xmlString.Length>0)
{
尝试
{
var serializer=新的DataContractSerializer(typeof(T));
使用(System.IO.MemoryStream memStm=new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString)))
{
return(T)serializer.ReadObject(memStm);
}
}
抓住
{
返回默认值(T);
}
}
其他的
返回默认值(T);
}
KeyValuePair就像一本字典:

public static string Serializza<T>(T objectToSerialize)
    {
        using (MemoryStream memStm = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memStm, objectToSerialize);

            memStm.Seek(0, SeekOrigin.Begin);

            using (var streamReader = new StreamReader(memStm))
            {
                string result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    private static T Deserializza<T>(string xmlString)
    {
        if (xmlString.Length > 0)
        {
            try
            {
                var serializer = new DataContractSerializer(typeof(T));
                using (System.IO.MemoryStream memStm = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString)))
                {
                    return (T)serializer.ReadObject(memStm);
                }
            }
            catch
            {
                return default(T);
            }
        }
        else
            return default(T);
    }
[Serializable, StructLayout(LayoutKind.Sequential)]
public class WritableKeyValuePair<TKey, TValue> : IWritableKeyValuePair
{
    private TKey key;
    private TValue value;

    public WritableKeyValuePair() { }
    public WritableKeyValuePair(TKey key, TValue value)
    {
        this.key = key;
        this.value = value;
    }

    public override string ToString()
    {
        return WKVPUtils<TKey, TValue>.ToString(key, value);
    }

    ////[XmlProcessDeep()]
    public TValue Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public TKey Key
    {
        get { return this.key; }
        set { this.key = value; }
    }

    internal static class WKVPUtils<TKey, TValue>
    {
        public static string ToString(TKey Key, TValue Value)
        {
            StringBuilder builder1 = new StringBuilder();
            builder1.Append('[');
            if (Key != null)
                builder1.Append(Key.ToString());
            builder1.Append(", ");
            if (Value != null)
                builder1.Append(Value.ToString());
            builder1.Append(']');
            return builder1.ToString();
        }
    }
}
[可序列化,结构布局(LayoutKind.Sequential)]
公共类WritableKeyValuePair:IWritableKeyValuePair
{
私钥;
私人价值;
public WritableKeyValuePair(){}
public WritableKeyValuePair(TKey,TValue值)
{
this.key=key;
这个值=值;
}
公共重写字符串ToString()
{
返回WKVPUtils.ToString(键,值);
}
////[xmlprocessdeph()]
公共价值
{
获取{返回this.value;}
设置{this.value=value;}
}
公钥
{
获取{返回this.key;}
设置{this.key=value;}
}
内部静态类WKVPUtils
{
公共静态字符串ToString(TKey、TValue值)
{
StringBuilder builder1=新的StringBuilder();
builder1.Append('[');
if(Key!=null)
builder1.Append(Key.ToString());
builder1.追加(“,”);
if(值!=null)
builder1.Append(Value.ToString());
builder1.Append(']');
返回builder1.ToString();
}
}
}
试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<Root>" +
                "<WritableKeyValuePairOfKeyContraenteArrayOfAddress>" +
                   "<key>" +
                      "<KeyContaente>123456</KeyContaente>" +
                   "</key>" +
                   "<value>" +
                      "<Address>Maple road 12</Address>" +
                      "<Address>Oak street 71</Address>" +
                   "</value>" +
                "</WritableKeyValuePairOfKeyContraenteArrayOfAddress>" +
                "</Root>";

            XElement elements = XElement.Parse(xml);

            Dictionary<string, List<string>> dict = elements.Descendants("WritableKeyValuePairOfKeyContraenteArrayOfAddress").Select(x => new
            {
                key = (string)x.Descendants("KeyContaente").FirstOrDefault(),
                values = x.Descendants("Address").Select(y => (string)y).ToList()
            }).GroupBy(x => x.key, y => y.values)
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串xml=
"" +
"" +
"" +
"123456" +
"" +
"" +
“枫树路12号”+
“橡树街71号”+
"" +
"" +
"";
XElement元素=XElement.Parse(xml);
Dictionary dict=elements.subjects(“WritableKeyValuePairofKeyContrenteArrayofAddress”)。选择(x=>new
{
key=(字符串)x.subjects(“keycontainte”).FirstOrDefault(),
values=x.Address(“地址”)。选择(y=>(字符串)y.ToList()
}).GroupBy(x=>x.key,y=>y.value)
.ToDictionary(x=>x.Key,y=>y.FirstOrDefault());
}
}
}
(代表OP发布)

这个问题解决了。我必须按如下方式编辑XML结构:

<WritableKeyValuePairOfKeyContraenteArrayOfAddress>
   <key>
      <KeyContaente>123456</KeyContaente>
   </key>
   <value>
      <Address>Maple road 12</Address>
      <Address>Oak street 71</Address>
   </value>
</WritableKeyValuePairOfKeyContraenteArrayOfAddress>

123456
枫树道12号
橡树街71号

以前我为每个
标记了
标记,现在只有一个打开和关闭
标记,包含多个
标记。

显示代码。具体如何序列化?具体如何反序列化?您正在谈论的这个KeyValuePair是什么?请参阅opFYI中的编辑:
visual studio
标记的内容为:“除非您对visual studio有特定的问题,而不仅仅是编码问题,否则不要使用此标记”。我已删除标记。我无法让它将“值”强制转换为目标类型:values=x.subjections(“RecapitoPolizza”)。选择(y=>(Allianz.Anagrafe.AnagraficquietAnzamentTo.RecapitoPolizza)y)。ToList()错误:无法将类型“XElement”转换为“RecapitoPolizza”。发布的xml代码中没有标记RecapitoPolizza。不知道你对我发布的代码做了什么更改。我需要查看更多的xml文件,以确定您更改我发布的代码的原因。“RecapitoPolizza”是“Address”,您必须使用xml中的确切标记名。