Thursday, 25 December 2014

Search for XML elements using LINQ



I have the following XML file :



<warehouse>
<cat id="computer">
<item>
<SN>1</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
<item>
<SN>22</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
</cat>
<cat id="Stationery">
<item>
<SN> 33 </SN>
<name>note books</name>
<quantity>250</quantity>
<description>Caterpiller</description>
<price>5 USD</price>
</item>
</cat>
<cat id="Furniture">
<item>
<SN> 1 </SN>
<name>dasd</name>
<quantity>asdasd</quantity>
<description>das</description>
<price>dasd</price>
</item>
<item>
<SN>44</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>

<item>
</cat>
</warehouse>


and i have the following web form page for generate queries :(i need reputation to insert image so i'll try to descrip it)



choose where to search : (dropdownlist)
insert sn : (textbox)
generate query: (button)
[labels]


I want to return (name,description,price,quantity) for SN==Textbox.text where <cat id= dropdownlist.text> in the label. can u help using LINQ or XPATH or any other methods.


I have tried this code , but i dont know to insert the SN==Textbox.text where <cat id= dropdownlist.text> condition into it !! please help me.



XDocument xmlDoc = XDocument.Load(Server.MapPath("/XML/Cat1.xml"));
var persons = from person in xmlDoc.Descendants("item")

select new
{
SN = person.Element("SN").Value,
name = person.Element("name").Value,
quantity = person.Element("quantity").Value,
description = person.Element("description").Value,
price = person.Element("price").Value,
};

foreach (var person in persons)
{
label1.Text = person.SN "<br />";
label2.Text = person.name"<br />";
label3.Text = person.description"<br />";
label4.Text = person.price"<br />";
label5.Text = person.quantity"<br />";
}

No comments:

Post a Comment