如何将 NameValueCollection 转换为 XML?

How to convert NameValueCollection to XML?

如何转换 NameValueCollection,例如:

  var mydata = new NameValueCollection();
    mydata.Add("UserID", "3698521478963");
    mydata.Add("Password", "23584");
    mydata.Add("VerifyCode", "23654");

到 XML 字符串,如下所示:

XML数据:

?

您可以使用 LINQ-to-XML 来实现,例如:

var mydata = new NameValueCollection();
mydata.Add("UserID", "3698521478963");
mydata.Add("Password", "23584");
mydata.Add("VerifyCode", "23654");

var result = new XElement("Root",
                            mydata.AllKeys.Select(o => new XElement(o, mydata[o]))
                         );
Console.WriteLine(result.ToString());

Dotnetfiddle Demo

输出:

<Root>
  <UserID>3698521478963</UserID>
  <Password>23584</Password>
  <VerifyCode>23654</VerifyCode>
</Root>