XML相关转换

1、将DataTable转换成xml字符串
      //将DataTable转换成xml字符串: public string ConvertDataTableToXml(DataTable dt) { MemoryStream stream = null; XmlTextWriter writer = null; try { stream = new MemoryStream(); writer = new XmlTextWriter(stream, System.Text.Encoding.Unicode); dt.WriteXml(writer); int count = (int)stream.Length; byte[] arr = new byte[count]; stream.Seek(0, SeekOrigin.Begin); stream.Read(arr, 0, count); System.Text.Encoding ucode = System.Text.Encoding.Unicode; //若使用utf-8,遇中文会发生乱码 return ucode.GetString(arr).Trim(); } catch { return String.Empty; } }

 2、将xml转换为字符串

//将xml转换为字符串

private String XmlDocToString(XmlDocument xmlDoc, String EncodeName)  //GBK

        {

            MemoryStream xmlstream = new MemoryStream();

            XmlTextWriter writer = new XmlTextWriter(xmlstream, Encoding.GetEncoding(EncodeName));

            writer.Formatting = Formatting.Indented;

            xmlDoc.Save(writer);

            StreamReader sr = new StreamReader(xmlstream, Encoding.GetEncoding(EncodeName));

            xmlstream.Position = 0;

            String strResult = sr.ReadToEnd();

            sr.Close();

            xmlstream.Close();

            writer.Close();

            return strResult;

        }

 

你可能感兴趣的:(xml)