添加三个控件,分别为textEdit1(输入文本内容),simpleButton1(代码写在这里面),labelControl1(显示转化为Xml的内容)。
代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
List<string> list = new List<string>();
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
string a = textEdit1.Text;
string xml = Amm(a);//调用Amm
if (xml !=null)
{
labelControl1.Text = xml;//转化后显示在Label中
}
}
/// <summary>
/// 将文本转化为xml
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static string Amm(string t)
{
using (MemoryStream me=new MemoryStream())
{
XmlTextWriter xmlWriter = new XmlTextWriter(me ,Encoding .GetEncoding ("UTF-8") );//指定UTF-8编码
XmlSerializer xmlSerializer = new XmlSerializer(t.GetType ());
xmlSerializer.Serialize(xmlWriter ,t );
xmlWriter.Close();
return Encoding .UTF8 .GetString (me .GetBuffer ()) ;
}
}
}
}
大哥们,我刚开始学C#,请多多指教!