XML文件是安全的,在程序中我们大多数的文件都是XML文件,但是对于用DOM解析XML文件熟练运用的还是很少,如何使用DOM解析VB.NET XML文件呢?在这里就和大家一起看一个案例分析吧!
#T#1、建立字符串写文件,XML是由<>>组成,实际上把所有字符形成后再写进文件中即可。但此类方法不适合大数据的操作。
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
- '生成根节点并把它设置为文件的根
- 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