Xml operation auxiliary class XmlUtil in asp.net

Source: Internet
Author: User

The Xml operation helper class mainly includes two major operations: Xml serialization and deserialization. The code is as follows:

The code is as follows: Copy code


Namespace Tmac. Utilities
{
/// <Summary>
/// Xml operation class
/// </Summary>
Public class XmlUtil
    {
/// <Summary>
/// Serialized object is xml (or byte stream)
/// </Summary>
/// <Param name = "obj"> </param>
/// <Returns> </returns>
Public static string XmlSerialize (object obj)
        {
String result = null;

Try
            {
XmlSerializer xmlSerializer = new XmlSerializer (obj. GetType ());
Using (MemoryStream stream = new MemoryStream ())
                {
XmlTextWriter xmlTextWriter = new XmlTextWriter (stream, new UTF8Encoding (false ));
XmlTextWriter. Formatting = Formatting. Indented;
XmlSerializer. Serialize (xmlTextWriter, obj );
XmlTextWriter. Flush ();
XmlTextWriter. Close ();
UTF8Encoding uTF8Encoding = new UTF8Encoding (false, true );
Result = uTF8Encoding. GetString (stream. ToArray ());
                }

            }
Catch (Exception ex)
            {
Throw new Exception ("Couldn't serialize object:" + obj. GetType (). Name, ex );
            }
Return result;
        }

/// <Summary>
/// Reverse sequence xml is an object
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "type"> </param>
/// <Param name = "xmlPath"> </param>
/// <Returns> </returns>
Public static T XmlDeserialize <T> (Type type, string xmlPath)
        {
T obj = default (T );

XmlSerializer xmlSerializer = new XmlSerializer (type );
Try
            {
Using (StreamReader sr = new StreamReader (xmlPath ))
                {
Obj = (T) xmlSerializer. Deserialize (sr );
                }
            }
Catch (Exception ex)
            {
Throw new Exception (String. Format ("Couldn't parse xml: {0}; Type: {1}", xmlPath, type. FullName), ex );
            }
Return obj;
        }
    }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.