教你運用DOM解析VB.NET XML文件
作者:佚名
這里介紹了利用DOM解析VB.NET XML文件的案例分析,案例主要范例以SQLSERVER的Northwind中Employee表進行示范,代碼詳細,喜歡用DOM解析XML文件的朋友看看。
XML文件是安全的,在程序中我們大多數(shù)的文件都是XML文件,但是對于用DOM解析XML文件熟練運用的還是很少,如何使用DOM解析VB.NET XML文件呢?在這里就和大家一起看一個案例分析吧!
#T#1、建立字符串寫文件,XML是由<>>組成,實際上把所有字符形成后再寫進文件中即可。但此類方法不適合大數(shù)據(jù)的操作。
2、XLST,相當與CSS,VB不適合。
3、DOM。
所以介紹的是使用DOM來寫VB.NET XML文件。以下范例以SQLSERVER的Northwind中Employee表進行示范。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()
- '生成一個XML DOMDocument對象
- Set tempDoc = New MSXML2.DOMDocument
- '生成根節(jié)點并把它設(shè)置為文件的根
- Set Root = tempDoc.createElement("employees")
- Set tempDoc.documentElement = Root
- '在節(jié)點上添加多個屬性
- 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é)點添加到根節(jié)點上去,并且為這個節(jié)點設(shè)置一個屬性
- 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
責任編輯:田樹
來源:
博客