Saturday 26 May 2018

XMLformatting in c#



Format the minify XML into readable way which help to view it properly and easy to read in C#. You can make your simple xml formatter by using the below few lines of code in C#.
static void Main(string[] args)
        {
            try
            {
                string xml = @"<?xml version='1.0' encoding='UTF - 8' ?><employees><employee><id>1</id><firstName>Leonardo</firstName>
            <lastName>DiCaprio</lastName><photo>https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr5EO4zbh_Vl_1W3Pxwo9ty6C7GZuDhME8KIVAXi0-PmFL-jRxzLS_mHhWjSwZARP2Uzq-ci7TvJR_3YO056bYOf1PBV7zS2TeNv8gYyt54xH8toD7vZu0kMKSVIijC4QEZy5rB0I8ujA/s200/Leonardo+Dicaprio7.jpg</photo>
            </employee><employee><id>2</id><firstName>Johnny</firstName><lastName>Depp</lastName>
            <photo>http://4.bp.blogspot.com/_xR71w9-qx9E/SrAz--pu0MI/AAAAAAAAC38/2ZP28rVEFKc/s200/johnny-depp-pirates.jpg</photo>
            </employee><employee><id>3</id><firstName>Hritik</firstName><lastName>Roshan</lastName><photo>http://thewallmachine.com/files/1411921557.jpg</photo>
            </employee></employees> ";


                XDocument doc = XDocument.Parse(xml);
                Console.WriteLine("Input will be {0} \n", xml.ToString());
                Console.WriteLine("==========================================================================");
                Console.WriteLine("Output will be {0} \n" , doc.ToString());
            }
            catch (Exception)
            {
                // Handle and throw if fatal exception here; don't just ignore them
               // return xml;
            }
        }

Below line is only useful which will parse the string into proper XML Format

XDocument doc = XDocument.Parse(xml);

You can see the output as like below. XML Format


No comments:

Post a Comment