Apr 26, 2012

How to opean and read xml file attributes in c#.net using for each loop

XML File:



 <books>
  <book name="let us c" price="300" author="ykanitkar" />
  <book name="let us c++" price="1300" author="Vamsi" />
  </books>

Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace Xml_ex
{
    public partial class Readxml : Form
    {
        public Readxml()
        {
            InitializeComponent();
        }

        private void Readxml_Load(object sender, EventArgs e)
        {

        }

        

        private void button2_Click(object sender, EventArgs e)
        {

            XmlDocument xmldoc = new XmlDocument();
            XmlNodeList xmlnodes;
            XmlNode node;
            string strDocelement = "";
            int i = 0;
            string str = null;
            string strXmlLoc = "C:\\Users\\vmunnamgi3\\Desktop\\books.xml";
            xmldoc.Load(strXmlLoc);
            node = xmldoc.DocumentElement;
            if (node.HasChildNodes)
            {
                foreach (XmlNode xmlWrknode in node.ChildNodes)
                {

                   // str = xmlWrknode.Attributes.GetNamedItem("name").Value.ToString().Trim();
                    str = xmlWrknode.Attributes.GetNamedItem("name").Value.ToString().Trim() + "_" + xmlWrknode.Attributes.GetNamedItem("price").Value.ToString().Trim() + "_" + xmlWrknode.Attributes.GetNamedItem("author").Value.ToString().Trim();
                    MessageBox.Show(str);
                }
            }
        }
    }
}

No comments:

Post a Comment