Search code examples
c#xmlstringstringbuilderxml-builder

XML Building in C# Windows or ASP Application


I am passing lot of XML Parameters from my application to the SQL Server (both windows and ASP.Net application)

Earlier i used to build XML using the based concatenation operator in string, similar to the one below.

string XmlDetails = string.Empty;
XmlDetails = "<APPLICATION><SEND>";
XmlDetails += "<ID>" + txtCardNo.Text.ToString() + "</ID>";
XmlDetails += "</SEND></APPLICATION>";

The application really used to hog memory and was really slow. I changes the concatenation method to String Builder class to build big XML.

 XmlDetails = string.Format("{0}<{1}>{2}</{1}>", "<APPLICATION><SEND>", "ID", txtCardNo.Text.ToString()); 
 XmlDetails = string.Format("{0}<{1}>{2}</{1}>{3}", XmlDetails, "PAYDET", txtPOSPaydet.Text.ToString(), "</SEND></APPLICATION>");

While using the above method there was a drastic change in the memory levels used by my application.

I would like to know if there are any better methods which could be employed in my application.


Solution

  • There are several options available to you:

    XElement, which allows you to handcraft your XML without having to build the string itself, but rather like so:

    XElement xmlTree1 = new XElement("Root",
        new XElement("Child1", 1),
        new XElement("Child2", 2),
        new XElement("Child3", 3)
    );
    
    Console.WriteLine(xmlTree2);
    

    This will write to the console:

    <Root>
      <Child1>1</Child1>
      <Child2>2</Child2>
      <Child3>3</Child3>
    </Root>
    

    If your XML format is static, you can also create an object representing your data, mark it as [Serializable], then serialize it:

    public static void Main(string[] args)
    {
        var myObjectToSerialize = new Root()
        {
            Child1 = 1,
            Child2 = 2,
            Child3 = 3
        };
    
        var serializer = new XmlSerializer(typeof(Root));
        serializer.Serialize(Console.Out, myObjectToSerialize);
        Console.ReadKey();
    }
    

    With the following class:

    [Serializable]
    public class Root
    {
        public int Child1 { get; set; }
    
        public int Child2 { get; set; }
    
        public int Child3 { get; set; }
    }