You are on page 1of 7

có lẻ các bro có người biết về cách sử lý XML và một số người thì không.

mình xin
viết một bài đơn giản về XML . có gì sai mong bỏ qua :D
<dataset>
<account ID="0" user="***" pass="***" desc="Admin">
<employee ID="05" Value="A(HCM)" />
<employee ID="04" Value="B(HCM)" />
<employee ID="03" Value="C(HCM)" />
<employee ID="02" Value="D(HCM)" />
<employee ID="01" Value="E(HN)" />
</account>
</dataset>
---------------------------------------------------------------------------
- reader.NodeType : có rất nhiều loại nodeType (XmlNodeType.Element,
XmlNodeType.CDATA)
- để đọc content( nội dung ) giữa 2 tag chúng ta sẽ được cung cấp hàm như sau:
+reader.ReadElementContentAsString()
+reader.ReadElementContentAsInt()
+.....
ví dụ : <website>daitiphu.com</website>
response.write(reader.ReadElementContentAsString()) --->daitiphu.com
-----------------------------------------------------------------------------
string strAccount = Request.PhysicalApplicationPath+ "xml\\adminLogin.xml";
string[] objUser = new string[6];
using (XmlReader reader = XmlReader.Create(strAccount))
{
while (reader.Read())
{

switch (reader.NodeType)
{
case XmlNodeType.Element:
//strValue += reader.Name.ToString() + "<br/>";
if (reader.Name == "account")
{
//nếu trong thẻ account có thuộc tính
if (reader.HasAttributes)
{
//bắt đầu đọc các thuộc tính
while (reader.MoveToNextAttribute())
{
if (reader.Name == "ID")
{
objUser[0] = reader.Value;
}
if (reader.Name == "user")
{
objUser[1] = reader.Value;
}
if (reader.Name == "pass")
{
objUser[2] = reader.Value;
}
if (reader.Name == "desc")
{
objUser[3] = reader.Value;
}
}
}
}
else if (reader.Name == "employee")
{
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "ID")
{
Response.Write(reader.Name + ":" + reader.Value
+ "<br/>");
}
if (reader.Name == "Value")
{
Response.Write(reader.Name + ":" + reader.Value
+ "<br/>");
}
}
}
}
break;
case XmlNodeType.CDATA:

break;

}
}
}

[C#]
private void WriteXmlToFile(DataSet thisDataSet) {
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "myXmlDoc.xml";
// Create the FileStream to write with.
System.IO.FileStream myFileStream = new System.IO.FileStream
(filename, System.IO.FileMode.Create);
// Create an XmlTextWriter with the fileStream.
System.Xml.XmlTextWriter myXmlWriter =
new System.Xml.XmlTextWriter(myFileStream,
System.Text.Encoding.Unicode);
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}

đặt ra 1 bài toán : bạn được bên A giao cho dữ liệu của 1 bảng (User) bằng XML và
yêu cầu bạn Insert toàn bộ dữ liệu đó vào DB của mình. Mình sẽ giải quyết như sau:

file.xml
<newForumAsh>
<user>
<userid>1</userid>
<username>admin</username>
<password>3349311e8bdb5b11d9f49ff2047e5631</password>
<email>admin@ash.com</email>
</user>
<user>
<userid>2</userid>
<username>user12</username>
<password>e493716f73d8e1c410bfbfe3e910d3af</password>
<email>user12@ash.com</email>
</user>
<user>
<userid>3</userid>
<username>user1</username>
<password>f65696f9d46fa5b8c70b2e20c045cdbf</password>
<email>user1@ash.com</email>
</user>
</newForumAsh>

trong trang aspx bạn tạo 1 form upload cho người dùng để upload file xml lên
sau đó trong code behind
aspx.vb

Public ValueInsert As Integer = 0


Private Sub btnImport_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles btnImport.Click
Try
Dim strEmail As String
Dim strPassword As String
Dim strUserName As String
'luu ra folder tam tren may chu
Dim strTempPath As String = Server.MapPath("~/Temp/")

'upload len folder tam


If fileUpload.HasFile Then
'chi upload file xml
If fileUpload.PostedFile.ContentType = "text/xml" Then
'luu xuong may chu
fileUpload.SaveAs(strTempPath & fileUpload.FileName)
'khoi tao dataset
Dim ds As DataSet = New DataSet()
'load file sau khi upload vao stream
Dim fsReadXml As System.IO.FileStream = New
IO.FileStream(strTempPath & fileUpload.FileName, IO.FileMode.Open)
'dataset doc file xml tu stream
ds.ReadXml(fsReadXml)
'dong stream
fsReadXml.Close()
'khoi tao 1 datatable de dua dataset vao
Dim dbTable As DataTable = ds.Tables(0)
'duyet den tung dong trong table
For Each row As DataRow In dbTable.Rows
'gan cho moi bien vao cac truong
strEmail = row("email").ToString()
strPassword = row("password").ToString()
strUserName = row("username").ToString()

If strEmail = vbNullString Then


strEmail = " "
End If

If strPassword = vbNullString Then


strPassword = " "
End If

If strUserName = vbNullString Then


strUserName = " "
End If

'tao user
Me.CreateUser(strUserName, strPassword, strEmail)
'tang gia tri insert len 1 sau moi lan insert
ValueInsert = ValueInsert + 1

Next
'xoa file vua upload sau khi import xong
File.Delete(strTempPath & fileUpload.FileName)
Response.Write("* Delete Temp File<br />")
'ok
Response.Write("* Import Complete<br />")
'ghi ra da insert bao nhieu ban ghi
Response.Write("* Insert " & ValueInsert.ToString() & "
records.<br />")
Else
Response.Write("* Please choose XML File")
End If
Else
Response.Write("* File Upload Require")
End If
Catch ex As Exception
Response.Write(ex.Message)
End Try
end sub

Public Sub CreateUser(ByVal NickName As String, ByVal Password As String, ByVal


Email As String, ByVal Salt As String)
Try
'khoi tao ket noi
dim dataConn As System.Data.SqlClient.SqlConnection
dim dataComm As System.Data.SqlClient.SqlCommand
If dataConn Is Nothing Then dataConn = New
System.Data.SqlClient.SqlConnection
'* neu trang thai cua dataConn la Closed thi moi mo them ket noi
If dataConn.State = ConnectionState.Closed Then
dataConn.ConnectionString = vbNullString
dataConn.ConnectionString = strDataString
dataConn.Open()
End If

If dataComm Is Nothing Then dataComm = New


System.Data.SqlClient.SqlCommand
dataComm.Connection = dataConn
dataComm.CommandTimeout = 20
dataComm.CommandType = CommandType.Text

'Query Insert
Dim strQuery As String = "INSERT INTO
[tbl_User]([UserName],[Password],[Email]) VALUES('" & NickName & "','" & Password &
"','" & Email & "')"
'Execute
dataComm.CommandText = strQuery
dataComm.ExecuteNonQuery()

'dong connect sau khi insert


If Not dataConn Is Nothing Then If dataConn.State = ConnectionState.Open
Then dataConn.Close()
dataConn = Nothing
Catch ex As Exception
Throw New ApplicationException(ex.Message)
End Try
End Sub

using System;
using System.Data;
using System.Data.SqlClient;

class WriteAndReadXML {
public static void Main() {
SqlConnection mySqlConnection = new SqlConnection("server=local
host;database=Northwind;uid=sa;pwd=sa");

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();


mySqlCommand.CommandText =
"SELECT TOP 2 CustomerID, CompanyName, ContactName, " +
"Address " +
"FROM Customers " +
"ORDER BY CustomerID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Customers");
mySqlConnection.Close();

myDataSet.WriteXml("myXmlFile.xml");

myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);

myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");

myDataSet.Clear();

myDataSet.ReadXml("myXmlFile.xml");

DataTable myDataTable = myDataSet.Tables["Customers"];


foreach (DataRow myDataRow in myDataTable.Rows) {
Console.WriteLine("CustomerID = " + myDataRow["CustomerID"]
);
Console.WriteLine("CompanyName = " + myDataRow["CompanyName"
]);
Console.WriteLine("ContactName = " + myDataRow["ContactName"
]);
Console.WriteLine("Address = " + myDataRow["Address"]);
}
}
}

Open the XML file and read into a DataSet

using System;
using System.IO;
using System.Data;

public class MainClass {


static void Main(string[] args) {
if (args.Length != 1)
return;

FileStream fs = new FileStream(args[0], FileMode.Open);


DataSet ds = new DataSet();
ds.ReadXml(fs);

// Use a DataTable to display the members.


DataTable mt = ds.Tables["member"];
for (int row = 0; row < mt.Rows.Count; row++) {
for (int col = 0; col < mt.Columns.Count - 1; col++) {
Console.WriteLine("{0,-10}{1}",
mt.Columns[col].Caption,
mt.Rows[row][col].ToString().Trim());
}
Console.WriteLine();
}
fs.Close();
}
}

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;

class Program {
static void Main(string[] args) {
DataSet thisDataSet = new DataSet();
thisDataSet.ReadXml("nwinddata.xml");

foreach (DataRow custRow in thisDataSet.Tables["Customers"].Row


s) {
Console.WriteLine("Customer ID: " + custRow["CustomerID"] +
" Name: " + custRow["CompanyName"]);
}

Console.WriteLine("Table created by ReadXml is called {0}",


thisDataSet.Tables[0].TableName);
}
}

You might also like