Part 2 : Reading Xml in C#.Net : XmlDocument

Namespace :  System.xml
Class name :XmlDocument()
Description 
This class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document. Because XmlDocument implements the IXPathNavigable interface it can also be used as the source document for the XslTransform class.
The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.
Coding :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml;//Xml Class
using System.Windows.Forms;
using System.IO;
namespace Xml_Sample
{
public partial class frmRead : Form
{
public frmRead()
{
InitializeComponent();
}

private void toolStripButton1_Click(object sender, EventArgs e)
{
op.ShowDialog();//open file dialog
this.toolStripTextBox1.TextBox.Text = op.FileName;
//load the xml file
if (this.toolStripTextBox1.TextBox.Text != string.Empty)
//read xml file
Read_Xml(this.toolStripTextBox1.TextBox.Text.Trim());
else
MessageBox.Show("Select Xml file"); 
}


public void Read_Xml(string filepath)
{
try{
//create new instance of class
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);//Loads xml file



//format the xml to show in richtextbox
string output=formatDocument(xdoc); 
 //Shows the xml 
this.richTextBox1.Text = output;
}

//If error Occured
catch (Exception ex)
{
//Show error message
MessageBox.Show(ex.Message, "Status Error",MessageBoxButtons.OK, MessageBoxIcon.Error); 

}

}

private string formatDocument(XmlDocument xdoc)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtxtWriter = new XmlTextWriter(sw);
xtxtWriter.Formatting = Formatting.Indented;
xdoc.WriteTo(xtxtWriter);
return(sb.ToString());
} 
}
}
Xml_Sample.rar 

posted under , , , |

0 comments:

Newer Post Older Post Home

We have seen by

    Followers

    Translate


Recent Comments