Page 1
//java2s.com
About Sample Example 1
In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output.
Sample Example 1.
using System;
using System.Xml;
namespace ReadXml1
{
class Class1
{
static void Main(string[] args)
{
// Create an isntance of XmlTextReader and call Read method to read the file
Page 2
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read())
{
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
// Read this element's properties and display them on console
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" + textReader.LocalName);
Page 3
Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
Console.WriteLine("Depth:" + textReader.Depth.ToString());
Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
}
}
}
}
About Sample Example 2
In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.
Sample Example 2.
Page 4
using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
int ws = 0;
int pi = 0;
int dc = 0;
int cc = 0;
int ac = 0;
Page 5
int et = 0;
int el = 0;
int xd = 0;
// Read a document
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
// Read until end of file
while (textReader.Read())
{
XmlNodeType nType = textReader.NodeType;
// If node type us a declaration
if (nType == XmlNodeType.XmlDeclaration)
{
Console.WriteLine("Declaration:" + textReader.Name.ToString());
Page 6
xd = xd + 1;
}
// if node type is a comment
if (nType == XmlNodeType.Comment)
{
Console.WriteLine("Comment:" + textReader.Name.ToString());
cc = cc + 1;
}
// if node type us an attribute
if (nType == XmlNodeType.Attribute)
{
Console.WriteLine("Attribute:" + textReader.Name.ToString());
ac = ac + 1;
}
Page 7
// if node type is an element
if (nType == XmlNodeType.Element)
{
Console.WriteLine("Element:" + textReader.Name.ToString());
el = el + 1;
}
// if node type is an entity\
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
et = et + 1;
}
// if node type is a Process Instruction
Page 8
if (nType == XmlNodeType.Entity)
{
Console.WriteLine("Entity:" + textReader.Name.ToString());
pi = pi + 1;
}
// if node type a document
if (nType == XmlNodeType.DocumentType)
{
Console.WriteLine("Document:" + textReader.Name.ToString());
dc = dc + 1;
}
// if node type is white space
if (nType == XmlNodeType.Whitespace)
{
Page 9
Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());
ws = ws + 1;
}
}
// Write the summary
Console.WriteLine("Total Comments:" + cc.ToString());
Console.WriteLine("Total Attributes:" + ac.ToString());
Console.WriteLine("Total Elements:" + el.ToString());
Console.WriteLine("Total Entity:" + et.ToString());
Console.WriteLine("Total Process Instructions:" + pi.ToString());
Console.WriteLine("Total Declaration:" + xd.ToString());
Console.WriteLine("Total DocumentType:" + dc.ToString());
Console.WriteLine("Total WhiteSpaces:" + ws.ToString());
Page 10
}
}
}
Writing XML Documents
About Sample Example 3
In this sample example, I create a new file myxmlFile.xml using
XmlTextWriter and use its various write methods to write XML items.
Sample Example 3.
using System;
using System.Xml;
namespace ReadingXML2
{
class Class1
{
Page 11
static void Main(string[] args)
{
// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);
// Opens the document
textWriter.WriteStartDocument();
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteComment("myXmlFile.xml in root dir");
// Write first element
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
// Write next element
Page 12
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
// Write one more element
textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");
textWriter.WriteEndElement();
// WriteChars
char[] ch = new char[3];
ch[0] = 'a';
ch[1] = 'r';
ch[2] = 'c';
textWriter.WriteStartElement("Char");
textWriter.WriteChars(ch, 0, ch.Length);
textWriter.WriteEndElement();
Page 13
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();
}
}
}
Writing Data from a database(SQL) to an XML Document
Sample Example 4.
using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
Page 14
namespace ReadingXML2
{
class Class1
{
static void Main(string[] args)
{
// create a connection
SqlConnection con = new SqlConnection();
con.ConnectionString = @"server = turgaypc\sqlexpress;integrated security = true;database = northwind";
// create a data adapter
SqlDataAdapter da = new SqlDataAdapter("Select * from Customers", con);
// create a new dataset
DataSet ds = new DataSet();
// fill dataset
da.Fill(ds, "Customers");
// write dataset contents to an xml file by calling WriteXml method
ds.WriteXml("g:\\OutputXML.xml");
}
}
}
//Example 5
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
Page 15
using System.Data;
using System.Data.OleDb;
using System.Xml;
public class DataGridXML : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
public DataGridXML()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.dataGrid1.DataMember = "";
this.dataGrid1.Location = new System.Drawing.Point(8, 16);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(264, 232);
this.dataGrid1.TabIndex = 0;
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] { this.dataGrid1 });
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
XmlDataDocument xmlDatadoc = new XmlDataDocument();
xmlDatadoc.DataSet.ReadXml("G:\\books.xml");
DataSet ds = new DataSet("Books DataSet");
Page 16
ds = xmlDatadoc.DataSet;
dataGrid1.DataSource = ds.DefaultViewManager;
}
static void Main()
{
Application.Run(new DataGridXML());
}
}
//Example 6
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Xml;
public class XmlDataGridForm : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dgLateXmlBound;
private System.Windows.Forms.Button cmdLoad;
private System.Windows.Forms.Button cmdSave;
Page 17
private XmlDataDocument xdocSnowReports;
private System.Windows.Forms.DataGridTableStyle dgsResorts;
private System.Windows.Forms.DataGridTextBoxColumn tbcResort;
private System.Windows.Forms.DataGridTextBoxColumn tbcSnowMin;
private System.Windows.Forms.DataGridTextBoxColumn tbcSnowHigh;
public XmlDataGridForm()
{
this.dgLateXmlBound = new System.Windows.Forms.DataGrid();
this.cmdLoad = new System.Windows.Forms.Button();
this.cmdSave = new System.Windows.Forms.Button();
this.dgsResorts = new System.Windows.Forms.DataGridTableStyle();
this.tbcResort = new System.Windows.Forms.DataGridTextBoxColumn();
this.tbcSnowMin = new System.Windows.Forms.DataGridTextBoxColumn();
this.tbcSnowHigh = new System.Windows.Forms.DataGridTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dgLateXmlBound)).BeginInit();
this.SuspendLayout();
//
// dgLateXmlBound
//
this.dgLateXmlBound.DataMember = "";
this.dgLateXmlBound.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgLateXmlBound.Name = "dgLateXmlBound";
this.dgLateXmlBound.Size = new System.Drawing.Size(432, 264);
this.dgLateXmlBound.TabIndex = 0;
this.dgLateXmlBound.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgsResorts});
Page 18
//
// cmdLoad
//
this.cmdLoad.Location = new System.Drawing.Point(8, 280);
this.cmdLoad.Name = "cmdLoad";
this.cmdLoad.TabIndex = 1;
this.cmdLoad.Text = "load";
this.cmdLoad.Click += new System.EventHandler(this.cmdLoad_Click);
//
// cmdSave
//
this.cmdSave.Location = new System.Drawing.Point(96, 280);
this.cmdSave.Name = "cmdSave";
this.cmdSave.TabIndex = 2;
this.cmdSave.Text = "save";
this.cmdSave.Click += new System.EventHandler(this.cmdSave_Click);
//
// dgsResorts
//
this.dgsResorts.DataGrid = this.dgLateXmlBound;
this.dgsResorts.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
this.tbcResort,
this.tbcSnowMin,
this.tbcSnowHigh});
this.dgsResorts.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgsResorts.MappingName = "Resort";
//
Page 19
// tbcResort
//
this.tbcResort.Format = "";
this.tbcResort.FormatInfo = null;
this.tbcResort.HeaderText = "Resort name";
this.tbcResort.MappingName = "Name";
this.tbcResort.Width = 75;
//
// tbcSnowMin
//
this.tbcSnowMin.Format = "";
this.tbcSnowMin.FormatInfo = null;
this.tbcSnowMin.HeaderText = "Min snow";
this.tbcSnowMin.MappingName = "SnowLow";
this.tbcSnowMin.Width = 75;
//
// tbcSnowHigh
//
this.tbcSnowHigh.Format = "";
this.tbcSnowHigh.FormatInfo = null;
this.tbcSnowHigh.HeaderText = "Max snow";
this.tbcSnowHigh.MappingName = "SnowHigh";
this.tbcSnowHigh.Width = 75;
//
// XmlDataGridForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
Page 20
this.ClientSize = new System.Drawing.Size(432, 309);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.cmdSave,
this.cmdLoad,
this.dgLateXmlBound});
this.Name = "XmlDataGridForm";
this.Text = "XML in DataGrid";
((System.ComponentModel.ISupportInitialize)(this.dgLateXmlBound)).EndInit();
this.ResumeLayout(false);
xdocSnowReports = new XmlDataDocument();
}
static void Main()
{
Application.Run(new XmlDataGridForm());
}
private void cmdLoad_Click(object sender, System.EventArgs e)
{
xdocSnowReports.DataSet.ReadXml(new StreamReader("G:\\Books.xml"), XmlReadMode.InferSchema);
dgLateXmlBound.SetDataBinding(xdocSnowReports.DataSet, "Book");
DataRow dr = xdocSnowReports.DataSet.Tables["Book"].Rows[0];
string strCaption = dr["Title"].ToString();
this.dgLateXmlBound.CaptionText = "Snow report on " + strCaption;
}
Page 21
private void cmdSave_Click(object sender, System.EventArgs e)
{
xdocSnowReports.DataSet.WriteXml("g:\\hardcodedfilename.xml");
}
}
Example 7
//Select nodes in RSS
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
class MainClass
{
static void Main(string[] args)
{
WebClient client = new WebClient();
string rssFeed = client.DownloadString("http://blogs.apress.com/wp-rss2.php");
XmlDocument doc = new XmlDocument();
doc.LoadXml(rssFeed);
XmlNodeList nodes = doc.SelectNodes("rss/channel/item/title");
foreach (XmlNode node in nodes)
Page 22
{
Console.WriteLine(node.InnerText);
}
}
}