整理以前旧问题,原帖地址:http://topic.csdn.net/t/20050628/16/4110312.html
1、建立字符串写文件,XML是由<></>组成,实际上把所有字符形成后再写进文件中即可。但此类方法不适合大数据的操作。
2、XLST,相当与CSS,VB不适合。
3、DOM。
所以介绍的是使用DOM来写XML文件。
以下范例以SQLSERVER的Northwind中Employee表进行示范。
代码如下:
Option Explicit
Public Rs As New ADODB.Recordset
Public Conn As New ADODB.Connection
Public tempDoc As MSXML2.DOMDocument 'xml文件
Public tempNode As MSXML2.IXMLDOMNode
Public Root As MSXML2.IXMLDOMElement
Public tempelement As MSXML2.IXMLDOMElement
Public tempattribute As MSXML2.IXMLDOMElement
Public emp As MSXML2.IXMLDOMElement
Private Sub Command1_Click()
'生成一个XML DOMDocument对象
Set tempDoc = New MSXML2.DOMDocument
'生成根节点并把它设置为文件的根
Set Root = tempDoc.createElement("employees")
Set tempDoc.documentElement = Root
'在节点上添加多个属性
Call Root.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
Call Root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
Call Root.setAttribute("xmlns", "http://www.kingdee.com/ReK3Inventory")
Do While Not Rs.EOF
Set emp = tempDoc.createNode(MSXML2.NODE_ELEMENT, "employee", "")
Root.appendChild emp
'生成孩子节点添加到根节点上去,并且为这个节点设置一个属性
Set tempNode = tempDoc.createNode(MSXML2.NODE_ELEMENT, "Employeeid", "")
tempNode.Text = Rs(0)
emp.appendChild tempNode
Set tempNode = tempDoc.createNode(MSXML2.NODE_ELEMENT, "Firstname", "")
tempNode.Text = Rs(1)
emp.appendChild tempNode
Set tempNode = tempDoc.createNode(MSXML2.NODE_ELEMENT, "Title", "")
tempNode.Text = Rs(2)
emp.appendChild tempNode
Rs.MoveNext
Loop
Dim pi As IXMLDOMProcessingInstruction
Set pi = tempDoc.createProcessingInstruction("xml", "version='1.0' encoding='gb2312'")
Call tempDoc.insertBefore(pi, tempDoc.childNodes(0))
'直接保存成文件即可
tempDoc.Save "c:\myTest.xml"
Unload Me
End Sub
Private Sub Form_Load()
'连接SQLSERVER
Dim strConn As String
strConn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Northwind;Data Source=LocalHost"
Conn.CursorLocation = adUseClient
Conn.Open strConn
If Rs.State <> adStateClosed Then Rs.Close
Rs.Open "Select employeeid,Firstname,Title from employees ", Conn, adOpenStatic, adLockOptimistic
End Sub
Private Sub Form_Unload(Cancel As Integer)
Rs.Close
Set Rs = Nothing
Conn.Close
Set Conn = Nothing
End Sub
MSDN中DOM的相关资料连接:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/89121802-adeb-4c14-9ed9-f4cd63c6619c.asp
发表于 @ 2007年04月23日 15:49:00|评论(loading...)|编辑