如何用VB.NET编写XML文档

今天在VB.NET社区看到“在vb.net中如何生成xml说明文档”这个问题!以前好象自己在处理类似情况也出现过这样或那样的问题。希望下面的东西能对大家有用处!

XMLTextWriter类包含所有简单地编写XML格式化文件所需要的例程。这个类会自动处理必要的操作,确定写入的文件是格式良好的XML文档。
使用XMLTextWriter类要遵循以下五个步骤:
1、创建新的XML流,并使用WriteStartDocument( )方法。这个方法会在文件中写入适当的XML声明。
2、用WriteStartElement( )方法写根数据元素。
3、在文件中写其余的元素。
4、用WriteEndElement( )方法关闭最后的元素。
5、用WriteEndDocument( ) 方法结束XML数据。调用这一方法很重要。该方法会关闭没有适当关闭的元素和其他结构。

以下代码:
在窗体文件的最开头:

Imports System.Xml

按钮的CLICK事件:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim myTW As New XmlTextWriter(Application.StartupPath & "\mytest.xml", Nothing)

myTW.WriteStartDocument()
myTW.Formatting = Formatting.Indented

myTW.WriteStartElement("Team")

myTW.WriteStartElement("player")
myTW.WriteAttributeString("Name", "George Zip")
myTW.WriteAttributeString("Position", "QB")
myTW.WriteElementString("Nickname", "Zippy")
myTW.WriteElementString("JerseyNumber", XmlConvert.ToString(7))

myTW.WriteEndElement()

myTW.WriteEndElement()

myTW.WriteEndDocument()

myTW.Close()
End Sub

执行程序,单击按钮后,在Bin文件夹下就会出现已经写好的 mytest.xml文档!

Published At
Categories with Web编程
Tagged with
comments powered by Disqus