Wednesday, 5 June 2013

.Net Tips : Create XElement or XML from string

We can construct or create XML or XElement from string. There are situations in applications where we receive some XML data in form of string and we need to convert that string back into the XML for our need and easy to handle that XML document for querying and other manipulation.
We are using "XElement.Parse" method to get XElement.

Here is example for this.
In this example we take one string xml and then we converted that in to XElement using "Parse" method of "System.Xml.Linq.XElement" Class.
You can see in output image that after parse that object we watch this object in "Text Visualizer" window and able to see that that string is converted in to XElement.

C#. Net Example :
        string strXML = "<Products>" +
                        "<Product id='1' price='5000'>CPU</Product>" +
                        "<Product id='2' price='500'>Monitor</Product>" +
                        "<Product id='2' price='100'>Mouse</Product>" +
                        "</Products>";
        System.Xml.Linq.XElement objXElement = System.Xml.Linq.XElement.Parse(strXML);
        Response.Write(objXElement);

VB.Net Examples :
        Dim strXML As String = "<Products>" & _
                                "<Product id='1' price='5000'>CPU</Product>" & _
                                "<Product id='2' price='500'>Monitor</Product>" & _
                                "<Product id='2' price='100'>Mouse</Product>" & "</Products>"
        Dim objXElement As System.Xml.Linq.XElement = System.Xml.Linq.XElement.Parse(strXML)
        Response.Write(objXElement)

Output : 
Create XElement or XML from string
(To view original image , click on image)

No comments:

Post a Comment

Post a Comment