11.01.2011

LINQ and XML From a String or Database

Sometimes we cannot always have XML from an XML file or Feed source and have to reply on a string or DB source. So what do we do?

Consider the following xml:




Home
http://www.example.com


My Link
http://www.example.com/SomePage.aspx




Suppose this xml is stored in our database or is present in a string. We can parse this as xml and query it using a LINQ.


Dim parsedXML As XDocument = XDocument.Parse(XMLString)

Dim Myitems = (From item In (From temp In parsedXML.Descendants("Menu") _
Select New With {.My_Page_Link = temp.Element("pageURL").Value, _
.Text_To_Display = temp.Element("text").Value _
}) Select item)


Here are some ideas on how we can play with the “MyItems” result set from above.

Simple Grid View



Bind with a grid view as:
        GridView1.DataSource = Myitems
        GridView1.DataBind()

And we have:



Simple Loop through the Results


        For i As Integer = 0 To Myitems.Count - 1
            Response.Write(Myitems(i).Text_To_Display)
            Response.Write(Myitems(i).My_Page_Link)
        Next


Store in a structure and return the custom structure through Function


    Public Structure MyCustomStructure
        Public LinkText As String
        Public PageHyperlink As String
    End Structure

And in a function
        Dim CustomStructure(Myitems.Count - 1) As MyCustomStructure
        Dim MyStructureHandle As MyCustomStructure

        For i As Integer = 0 To Myitems.Count - 1
            MyStructureHandle = New MyCustomStructure

            MyStructureHandle.LinkText = Myitems(i).Text_To_Display
            MyStructureHandle.PageHyperlink = Myitems(i).My_Page_Link

            CustomStructure(i) = MyStructureHandle
        Next

        Return CustomStructure

And with the returned function you can loop through or bind with a data display object.


How about searching the string XML?


you can easily search as:

        Dim Myitems = (From item In (From temp In parsedXML.Descendants("Menu") _
                                   Select New With {.My_Page_Link = temp.Element("pageURL").Value, _
                                                    .Text_To_Display = temp.Element("text").Value _
                                                   }) _
                        Where (item.My_Page_Link = "http://www.example.com") _
                        Select item)




Happy Programming!

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

 
POPULAR POSTS
TAG CLOUD