ĐỌC TÀI LIỆU XML
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//tạo 1 bộ đọc tập tin C:\data.xml
XmlTextReader textReader = new XmlTextReader("C:\\data.xml");
//trong khi nút có giá trị thì in ra những thuộc tính của nó
while (textReader.Read())
{
//chuyển đến phần tử đầu tiên
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
//đọc những thuộc tính của phần tử này và hiển thị nó lên màn hình
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" + textReader.LocalName);
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());
}
}
}
}
VIẾT XML
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//tạo một tập tin XML mới
XmlTextWriter textWriter = new XmlTextWriter("C:\\firstXMLFile.xml", null);
//mở tài liệu
textWriter.WriteStartDocument();
//Viết 1 dòng chú thích vào tài liệu
textWriter.WriteComment("Chương trình XML đầu tiên của tôi");
//Viết nút gốc
textWriter.WriteStartElement("Student");
//Viết phần tử đầu
textWriter.WriteStartElement("r", "RECORD", "urn:record");
//viết phần tử thứ 2
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
//Viết phần tử thứ 3
textWriter.WriteStartElement("Address", "");
textWriter.WriteString("Colony");
textWriter.WriteEndElement();
//Viết mảng ký tự vào phần tử thứ 4
char[] ch = new char[3];
ch[0] = 'w';
ch[1] = 'i';
ch[2] = 'n';
textWriter.WriteStartElement("MangKyTu");
textWriter.WriteChars(ch, 0, ch.Length);
textWriter.WriteEndElement();
//kết thúc tài liệu
textWriter.WriteEndDocument();
//không viết nữa
textWriter.Close();
}
}
}