XELEMENT and XDOCUMENT


XML:

<CONTACTS>

<Contact ContactID=”2″>

<FirstName=”Arpit”/>

<LastName=”Gupta”/>

</CONTACTS>

XELEMENT: (located in System.xml.linq)

XElement xml = new XElement(“CONTACTS”, new XElement(“Contact”, new XAttribute(“ContactID”,”2″), new XAttribute(“FirstName”,”Arpit”), new XAttribute(“LastName”,”Gupta”)));

C# Code :

Loads XML from a local file into an XDocument Object

XDocument xmlDoc = XDocument.Load(@”C:sites.xml”);

Var q = from c in xmlDoc.Descendants(“site”)

select (string)c.Element(“name”) + “–” + (string)c.Element(“url”);

foreach (string name in q)

{

console.writeline(“site:” + name);

}

XML:

<Sites>

<site technical=”true”>

<name>Arpit</name>

<url>good2seeu.wordpress.com</url>

</site>

<site technical=”true”>

<name>Arpit_ABC</name>

<url>google.com</url>

</site>

</Sites>

XDocument is used to select the items to display VIADescendants” property in the “from” clause. Finally, “foreach” block is used to loop through  every Element loaded viaselect” statement and displayed viaconsole” object.

Filter VIA Where Clause:

Code snippets selects and display only those site elements with “TRUE” valus in its Technical Attributes.

XDocument XDoc = XDocument.load(@”C:Sites.xml”);

Var q= from c in XDoc.Descendants(“site”)

where c.Attribute(“Technical”).Value = “true”

select (string)c.Element(“name”) + “==>” + (string)c.Element(“url”);

foreach(string name in q)

{

console.writeline(“site:” + name);

}

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