教你運(yùn)用DOM解析VB.NET XML文件
XML文件是安全的,在程序中我們大多數(shù)的文件都是XML文件,但是對(duì)于用DOM解析XML文件熟練運(yùn)用的還是很少,如何使用DOM解析VB.NET XML文件呢?在這里就和大家一起看一個(gè)案例分析吧!
#T#1、建立字符串寫文件,XML是由<>>組成,實(shí)際上把所有字符形成后再寫進(jìn)文件中即可。但此類方法不適合大數(shù)據(jù)的操作。
2、XLST,相當(dāng)與CSS,VB不適合。
3、DOM。
所以介紹的是使用DOM來(lái)寫VB.NET XML文件。以下范例以SQLSERVER的Northwind中Employee表進(jìn)行示范。VB.NET XML文件代碼如下: 
- Option Explicit
 - Public RsAs New ADODB.Recordset
 - Public Conn As New ADODB.Connection
 - Public tempDocAs 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()
 - '生成一個(gè)XML DOMDocument對(duì)象
 - Set tempDoc = New MSXML2.DOMDocument
 - '生成根節(jié)點(diǎn)并把它設(shè)置為文件的根
 - Set Root = tempDoc.createElement("employees")
 - Set tempDoc.documentElement = Root
 - '在節(jié)點(diǎn)上添加多個(gè)屬性
 - 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
 - '生成孩子節(jié)點(diǎn)添加到根節(jié)點(diǎn)上去,并且為這個(gè)節(jié)點(diǎn)設(shè)置一個(gè)屬性
 - 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
 















 
 
 
 
 
 
 