转换一个IEnumerable>对象转换为XML
本文关键字:对象 转换 XML 字符串 一个 IEnumerable KeyValuePair | 更新日期: 2023-09-27 18:17:29
我需要将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";
}
}
有什么建议吗
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