2010年12月7日 星期二

vb.net xml操作實例

Imports System.Xml
Module Module1

Sub Main()
Dim xmlDocument As Xml.XmlDocument = New XmlDocument()
xmlDocument.Load("Student.xml")
Dim xmlnode As XmlNode
xmlnode = xmlDocument.DocumentElement

Dim xmlnode1 As XmlNode = xmlnode.SelectSingleNode("student/sname")
Console.WriteLine(xmlnode1.InnerText)
Dim xmlnode2 As XmlNodeList = xmlnode.SelectNodes("student")
Dim xn As XmlNode
For Each xn In xmlnode2
Console.WriteLine(xn.InnerText)
Next
Dim xmlnode3 As XmlElement = xmlDocument.createElement_x("student")
xmlnode3.SetAttribute("firstname", "張")
xmlnode3.SetAttribute("lastname", "無忌")
Dim node1 As XmlElement = xmlDocument.createElement_x("sid")
node1.InnerText = "005"
xmlnode3.AppendChild(node1)
Dim node2 As XmlElement = xmlDocument.createElement_x("sname")
node2.InnerText = "趙敏"
xmlnode3.AppendChild(node1)
Dim node3 As XmlElement = xmlDocument.createElement_x("score")
node3.InnerText = "78"
xmlnode3.AppendChild(node1)
xmlnode3.AppendChild(node2)
xmlnode3.AppendChild(node3)
xmlnode.AppendChild(xmlnode3)
xmlDocument.Save("Student.xml")
Console.WriteLine("節點添加完成!")
Dim ndlist As XmlNodeList = xmlDocument.SelectSingleNode("Students").ChildNodes
For Each nd As XmlNode In ndlist
Dim xe As XmlElement
xe = CType(nd, XmlElement)

If xe.GetAttribute("lastname") = "無忌" Then
xe.SetAttribute("firstname", "謝")


End If


If xe.ChildNodes(0).InnerText = "005" Then
nd.RemoveChild(xe.ChildNodes(1))
xmlnode.RemoveChild(nd)
Console.WriteLine("修改完成!")
Else
Console.WriteLine("沒有找到相關節點")
End If



xe.RemoveAll()




xmlDocument.Save("Student.xml")
Next
Console.WriteLine(xmlnode3.GetAttribute("lastname"))
Console.ReadLine()

End Sub

End Module

沒有留言:

張貼留言