转换IEnumerable <keyvaluepair <string,object =“”>&gt;对象到XML </keyvaluepair <string,>

时间:2013-06-06 21:25:00

标签: c# xml-serialization

我需要将IEnumerable对象转换为XML字符串

IEnumerable<KeyValuePair<string, object>>  myObject 

我尝试使用以下代码,但这不起作用

ConvertToXmlString(myObject);

public static string ConvertToXmlString(object name)
        {
            try
            {
                var stringwriter = new System.IO.StringWriter();
                var serializer = new XmlSerializer(name.GetType());
                serializer.Serialize(stringwriter, name);
                return stringwriter.ToString();
            }
            catch
            {
                return "cannot be converted to XML";
            }
        }

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

IEnumerable<KeyValuePair<string, object>>  myObject = ... 
XElement el = new XElement("root",
    myObject.Select(kv => new XElement(kv.Key, kv.Value)));
el.Save("myFile.xml"); // if you need to save it to file