我需要将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";
}
}
有什么建议吗?
答案 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