Chitika

Wednesday, November 21, 2012

Read XML data by attribute in C#


How to create XML document programmatically which i have shown in my previous XML article.
In this example i am going to show you, how to read data from XML document based on the value in c#. Use method XmlNode.Selec­tNodes to get list of nodes selected by the XPath expression. 
Check the  XML file.

<Products>
    <Product Category="0">LG DVD Writer</Name>
    <Product Category="1">I Ball Camera</Name>
    <Product Category="0">LG Monitor</Name>
    <Product Category="1">Creative Speakers</Name>
    <Product Category="0">Intel Mother Board</Name>
    <Product Category="1">Transcend Ram</Name>
    <Product Category="0">HCL Monitor</Name>
    <Product Category="1">Dell Laptop</Name>
    <Product Category="0">Sony DVD Writer</Name>
</Products>


To get all product nodes use XPath expression /Products/Product
To get only 1 category (to select all nodes with specific XML attribute) use XPath expression /Products/Product [@ Category ='1'].
[C#]

XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Products/Product[@category='1']");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

The output is:
I Ball Camera
Creative Speakers
Transcend Ram
Dell Laptop

No comments:

Post a Comment