Linq to XML

Here is an example of Linq to XML

<code>

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Collections.Generic;

using System.Linq;

using System.Xml;

using System.Xml.Linq;

string strXML = string.Empty;

#region set dummy xml

strXML = @”

<Table>

<Type>txt</Type>

<Name>testwewe.txt</Name>

<FilePath>aHR0cDovL2hkaGFwcH

<VersionNo.>3

</Table>

<Table>

<Type>txt</Type>

<Name>testwe.txt</Name>

<FilePath>YUhSMGNEb3ZMMmhrYU</FilePath>

<VersionNo.>3</VersionNo.>

</Table>

<Table>

<Type>txt</Type>

<Name>test.txt</Name>

<FilePath>YUhSMGNEb3ZMMmhrYU</FilePath>

<VersionNo.>3</VersionNo.>

</Table>

</NewDataSet>

“;

#endregion

XmlDocument xDoc1 = new XmlDocument();

xDoc1.LoadXml(strXML);

XDocument xmlSource = new XDocument(DocumentExtensions.ToXDocument(xDoc1));

var q =( from c in xmlSource.Descendants(“Table”)

where ((int)c.Element(“VersionNo.”) > 2)

select new { name = c.Element(“Name”).Value, filepath = c.Element(“FilePath”).Value });

foreach (var s in q)

{

if(!string.IsNullOrEmpty(s.name.ToString())

&& !string.IsNullOrEmpty(s.filepath.ToString()))

Response.Write(“Name: ” + s.name.ToString() + ” Filepath : =” + s.filepath.ToString());

}

public static class DocumentExtensions

{

public static XmlDocument ToXmlDocument(this XDocument xDocument)

{ var xmlDocument = new XmlDocument(); using (var xmlReader = xDocument.CreateReader()) { xmlDocument.Load(xmlReader); } return xmlDocument; }

public static XDocument ToXDocument(this XmlDocument xmlDocument)

{

using (var nodeReader = new XmlNodeReader(xmlDocument))

{

nodeReader.MoveToContent();

return XDocument.Load(nodeReader);

}

}

}

</code>

</pre>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s