user786
user786

Reputation: 4364

LINQ to XML's select is not working

I have a xml and I am using LINQ to XML to retrieve data from XML file.

following is my LINQ code

XElement newCustOrd = new XElement("ad",
from c in custOrd.Element("ad").Elements("adinfo")
where ((string)c.Attribute("title")).Contains("Android")
select new XElement("adinfo",
    new XElement("title", (string)c.Attribute("title")),
    new XElement("phone", (string)c.Attribute("phone")),
    new XElement("email", (string)c.Attribute("email"))
)
);

The problem my select statement in the query is only retrieving first element in XML file.

the element whose title contains Android is element number 4.

Any help will be appreciated

Following is my XML file's content

<ads>
 <ad id="bcc0d6dd-75c6-4e18-8318-a9defc8c0216" date="4/16/2016 4:00:16 AM">
   <adinfo title="Wanted: iPod 5" email="[email protected]" phone="7803051822" rod="" rprice="Please contact" rat="Wanted" cdetails="" address="5204 52 Ave, Rocky Mountain House, AB T4T 1G8" postal="T4T 1G8" description="Wanted: iPod 5" />
    <adimg>
     <img main="T" src="fede4afa-9f62-4cb5-a215-9e8714247416.jpg" />
     <img main="F" src="" />
</adimg>
</ad>
 <ad id="8482fcb2-8fb0-4e7e-9b51-4ed77ac3cd5f" date="4/6/2016 1:12:44 AM">
   <adinfo title="Sharp 50&quot; TV, LC-50LB261U, little over a year old" email="[email protected]" phone="7802391211" rod="" rprice="475" rat="Offering" cdetails="" address="   Edmonton, AB T5T6J9" postal="T5T6J9" description="Sharp 50&quot; TV, LC-50LB261U, little over a year old" />
 <adimg>
    <img main="T" src="2108fcd5-1074-4bbe-9d66-a69fe6b4216f.jpg" />
    <img main="F" src="" />
</adimg>
</ad>
<ad id="4b6d750d-2bd9-4382-8a45-c580f94c23ad" date="3/30/2016 1:31:26 AM">
  <adinfo title="BEST GIFT!! FREE TV AND MOVIES FOREVER!! - FREE KEYBOARD!!" email="[email protected]" phone="780-293-8574" rod="" rprice="149" rat="Offering" cdetails="" address="4817 118 Ave NW, Edmonton, AB T5W 1B5" postal="T5W 1B5" description="BEST GIFT!! FREE TV AND MOVIES FOREVER!! - FREE KEYBOARD!!" />
 <adimg>
   <img main="T" src="0c79e71f-382c-4e69-83b5-c6ce27044fb7.jpg" />
   <img main="F" src="" />
 </adimg>
</ad>
<ad id="aad706c0-1722-457e-bbb4-58b5abe1145e" date="3/18/2016 12:59:50 AM">
 <adinfo title="Android TV Boxes Are Better! Credit Cards Accepted." email="[email protected]" phone="780-887-8978" rod="" rprice="119.99" rat="Offering" cdetails="" address="   Strathcona County, AB T8H2G8" postal="T8H2G8" description="Android TV Boxes Are Better! Credit Cards Accepted." />
  <adimg>
    <img main="T" src="de5cc90a-6e47-4bed-81a1-eec8945f4495.jpg" />
    <img main="F" src="" />
 </adimg>
</ad>

Upvotes: 0

Views: 64

Answers (1)

har07
har07

Reputation: 89285

Use Elements() instead of singular Element() in custOrd.Element("ad") if you meant to get all <ad> elements instead of only the first.

Upvotes: 2

Related Questions