Professional Documents
Culture Documents
XML Read Write
XML Read Write
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
'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
'Query Insert
Dim strQuery As String = "INSERT INTO
[tbl_User]([UserName],[Password],[Email]) VALUES('" & NickName & "','" & Password &
"','" & Email & "')"
'Execute
dataComm.CommandText = strQuery
dataComm.ExecuteNonQuery()
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");
myDataSet.WriteXml("myXmlFile.xml");
myDataSet.WriteXml("myXmlFile2.xml", XmlWriteMode.WriteSchema);
myDataSet.WriteXmlSchema("myXmlSchemaFile.xml");
myDataSet.Clear();
myDataSet.ReadXml("myXmlFile.xml");
using System;
using System.IO;
using System.Data;
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");