VBNet中用XML替代INI配置功能的完整教程

合集下载

利用VB操作XML数据

利用VB操作XML数据

利用VB操作XML数据在VB中,有几种方法可以操作XML数据。

下面将介绍一些常用的方法:1. 创建XML文档:可以使用XMLTextWriter类或XDocument类来创建XML文档。

使用XMLTextWriter类:```vbDim writer As New XmlTextWriter("C:\path\to\file.xml", System.Text.Encoding.UTF8)writer.WriteStartDocument(True)writer.Formatting = Formatting.Indentedwriter.Indentation = 2writer.WriteStartElement("RootElement")writer.WriteEndElementwriter.WriteEndDocumentwriter.Close```使用XDocument类:```vbDim doc As XDocument = New XDocumentNew XDeclaration("1.0", "utf-8", "yes"),New XElement("RootElement")doc.Save("C:\path\to\file.xml")```2. 读取XML文档:可以使用XmlDocument类、XmlReader类或XDocument类来读取XML文档。

使用XmlDocument类:```vbDim doc As New XmlDocumentdoc.Load("C:\path\to\file.xml")Dim root As XmlNode = doc.SelectSingleNode("RootElement")```使用XmlReader类:```vbDim reader As XmlReader =XmlReader.Create("C:\path\to\file.xml")While reader.ReadIf reader.NodeType = XmlNodeType.Element AndAlso = "RootElement" Then'处理根元素End IfEnd Whilereader.Close```使用XDocument类:```vbDim doc As XDocument = XDocument.Load("C:\path\to\file.xml") Dim root As XElement = doc.Element("RootElement")```使用XmlDocument类:```vbDim doc As New XmlDocumentdoc.Load("C:\path\to\file.xml")Dim root As XmlNode = doc.SelectSingleNode("RootElement")Dim childElement As XmlElement =doc.CreateElement("ChildElement")Dim attribute As XmlAttribute =doc.CreateAttribute("AttributeName")attribute.Value = "AttributeValue"childElement.Attributes.Append(attribute)root.AppendChild(childElement)doc.Save("C:\path\to\file.xml")```使用XmlReader类:```vbDim reader As XmlReader =XmlReader.Create("C:\path\to\file.xml")While reader.ReadIf reader.NodeType = XmlNodeType.Element AndAlso = "RootElement" ThenDim childElement As XmlWriter =reader.CreateElement("ChildElement")writer.WriteAttributeString("AttributeName", "AttributeValue")writer.WriteEndElementEnd IfEnd Whilereader.Close```使用XDocument类:```vbDim doc As XDocument = XDocument.Load("C:\path\to\file.xml") doc.Root.Add(New XElement("ChildElement", NewXAttribute("AttributeName", "AttributeValue")))doc.Save("C:\path\to\file.xml")```以上是操作XML数据的一些基本方法,可以根据需求进行扩展。

VB如何操作INI文件方法详解

VB如何操作INI文件方法详解

VB如何操作INI文件方法详解在程序中经常要用到设置或者其他少量数据的存盘,以便程序在下一次执行的时候可以使用,比如说保存本次程序执行时窗口的位置、大小、一些用户设置的数据等等,在Dos 下编程的时候,我们一般自己产生一个文件,由自己把这些数据写到文件中,然后在下一次执行的时候再读出来使用。

在Win32 编程中当然你也可以这样干,但Windows 已经为我们提供了两种方便的办法,那就是使用注册表或者ini 文件(Profile)来保存少量数据。

本文中先介绍一下 .ini 文件的使用。

ini 文件是文本文件,中间的数据格式一般为:[Section1 Name]KeyName1=value1KeyName2=value2...[Section2 Name]KeyName1=value1KeyName2=value2ini 文件可以分为几个 Section,每个 Section 的名称用 [] 括起来,在一个 Section 中,可以有很多的 Key,每一个 Key 可以有一个值并占用一行,格式是 Key=value,Win32 对 ini 文件操作的 api 中,有一部分是对 win.ini 操作的,有一部分是对用户自定义的 ini 文件操作的。

Win.in 和 system.ini 是Windows的两个非常重要的初始化文件,Windows将用户所作的选择以及各种变化的系统信息记录在这两个文件中。

System.ini 描述了系统硬件的当前状态,Win.ini 文件则包含了Windows 系统运行环境的当前配置。

由于 Win.ini 文件的重要性和常用性,Win32 中有专门对 Win.ini 进行操作的 api,它们是:GetProfileInt - 从 Win.ini 文件的某个 Section 取得一个 key 的整数值,它的原形是:GetProfileInt(LPCTSTR lpAppName, // 指向包含 Section 名称的字符串地址LPCTSTR lpKeyName, // 指向包含 Key 名称的字符串地址INT nDefault // 如果 Key 值没有找到,则返回缺省的值是多少);如果 Key 值没有找到的话,返回值是 nDefault 指定的缺省值,如果 Key 中的值是负数,则返回 0,如果 Key 指定的是数字和字符串的混合,则返回数字部分的值,比如说 x=1234abcd,则返回 1234GetProfileString - 从 Win.ini 文件的某个 Section 取得一个 key 的字符串,它的原形是:GetProfileString(LPCTSTR lpAppName, // 指向包含 Section 名称的字符串地址LPCTSTR lpKeyName, // 指向包含 Key 名称的字符串地址LPCTSTR lpDefault, // 如果 Key 值没有找到,则返回缺省的字符串的地址LPTSTR lpReturnedString, // 返回字符串的缓冲区地址DWORD nSize // 缓冲区的长度);返回的字符串在缓冲区内,返回的eax 值是返回的字符串的长度(不包括尾部的0)GetProfileSection - 从 Win.ini 文件中读出整个 Section 的内容,它的原形是:GetProfileSection(LPCTSTR lpAppName, // 指向包含 Section 名称的字符串地址LPTSTR lpReturnedString, // 返回数据的缓冲区地址DWORD nSize // 返回数据的缓冲区长度);WriteProfileSection - 将一个整个 Section 的值写入 Win.ini 文件的指定 Section 中,它的原形是:WriteProfileSection(LPCTSTR lpAppName, // 指向包含 Section 名称的字符串地址LPCTSTR lpString // 要写入的数据的地址);如果 Win.ini 没有指定的 Section,API 会新建立一个并写入数据,如果已经存在,则先删除原来 Seciton 中所有的 Key 值然后写入新的。

VB.NET读写XML配置文件

VB.NET读写XML配置文件

读写XML配置⽂件XML配置⽂件代替INI()Imports System.DataPublic Class CLSReadXMLPrivate servername As String'服务器名Private Dbname As String'数据库名称Private Uid As String'数据库⽤户名Private pwd As String'数据库密码Private DSXml As New DataSetPrivate Xpath As String'Xml⽂件路径Sub New(ByVal str As String)Xpath = str'获得xml⽂件存储路径End Sub#Region "属性⽤于写⼊和得到xml⽂件内容的属性"Public Property Getserver()GetReturn servernameEnd GetSet(ByVal Value)servername = ValueEnd SetEnd PropertyPublic Property Getdbname()GetReturn DbnameEnd GetSet(ByVal Value)Dbname = ValueEnd SetEnd PropertyPublic Property Getpwd()GetReturn pwdEnd GetSet(ByVal Value)pwd = ValueEnd SetEnd PropertyPublic Property GetdUid()GetReturn UidEnd GetSet(ByVal Value)Uid = ValueEnd SetEnd Property#End Region#Region "⽅法读写xml⽂件的⽅法当xml⽂件不存在时⾃动创建⼀xml⽂件"'读取xml⽂件内容Public Function ReadXml() As BooleanTryDSXml.ReadXml(Xpath)servername = DSXml.Tables(0).Rows(0)("server")Dbname = DSXml.Tables(0).Rows(0).Item("Dbname")Uid = DSXml.Tables(0).Rows(0).Item("uid")pwd = DSXml.Tables(0).Rows(0).Item("pwd")Return TrueCatch ex As ExceptionThrow exReturn FalseEnd TryEnd Function'如果xml⽂件不存在的时候创建⼀xml⽂件Public Function WriteXml() As BooleanDim DT As New DataTableTryDSXml.Tables.Clear()DSXml.Clear()'给定table列框架DT.Columns.Add("server", GetType(String))Dt.Columns.Add("DBname", GetType(String))Dt.Columns.Add("uid", GetType(String))Dt.Columns.Add("pwd", GetType(String))Dim DR As DataRowDR = Dt.NewRowDR.Item("server") = servername DR.Item("DBname") = Dbname DR.Item("uid") = UidDR.Item("pwd") = pwdDt.Rows.Add(DR)DSXml.Tables.Add(Dt)DSXml.AcceptChanges()DSXml.WriteXml(Xpath)Return TrueCatch ex As ExceptionThrow exReturn FalseEnd TryEnd Function#End RegionEnd Class。

VB.NET读取写入XML文件

VB.NET读取写入XML文件

读取写入XML文件Public Class CSysXMLDim mXmlDoc As New System.Xml.XmlDocumentPublic XmlFile As StringPublic Sub New(ByVal File As String)MyClass.XmlFile = FileMyClass.mXmlDoc.Load(MyClass.XmlFile) '加载配置文件End Sub'功能:取得元素值'参数:node--节点 element--元素名'返回:元素值字符型' $--表示出错误Public Function GetElement(ByVal node As String, ByVal element As String) As StringOn Error GoTo ErrDim mXmlNode As System.Xml.XmlNode = mXmlDoc.SelectSingleNode("//" + node)'读数据Dim xmlNode As System.Xml.XmlNode = mXmlNode.SelectSingleNode(element)Return xmlNode.InnerText.T oStringErr:Return "$"End Function''功能:保存元素值'参数:node--节点名称 element--元素名 val--值'返回:True--保存成功 False--保存失败Public Function SaveElement(ByVal node As String, ByValelement As String, ByVal val As String) As BooleanOn Error GoTo errDim mXmlNode As System.Xml.XmlNode = mXmlDoc.SelectSingleNode("//" + node)Dim xmlNodeNew As System.Xml.XmlNodexmlNodeNew = mXmlNode.SelectSingleNode(element)xmlNodeNew.InnerText = valmXmlDoc.Save(MyClass.XmlFile)Return Trueerr:Return FalseEnd FunctionEnd Class例如:XML:192.168.0.6程序调用:Public Class Form1Dim xml As New CSysXML("IP.xml")Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim str As String = xml.GetElement("IP", "num")TextBox1.Text = strEnd SubEnd Class。

VB和VB_NET中的XML操作

VB和VB_NET中的XML操作

2. 数据交换和数据整合,这是XML最激动人心的应用。
3. 媒体无关的数据发布
4. 智能代理和本地计算
5. 精确搜索
6. 文件保值
XML的语法非常的简单,XML文档由节点组成,使用打开和关闭节点描述标记,在格式上与HTML标记非常相似,它们之间最大的不同是:XML中可以自由定义标记名。比如下面的标记就描述了一个主页地址:
概述:这篇文章为计划将他们的应用程序更新到Visual 的微软Visual Basic 开发用户提供一些关于XML的建议。主要包括Visual Basic 6和Visual 对XML操作的不同之处,以及Visual 关于这方面新增工具的应用。 概述:这篇文章为计划将他们的应用程序更新到Visual 的微软Visual Basic 开发用户提供一些关于XML的建议。主要包括Visual Basic 6和Visual 对XML操作的不同之处,以及Visual 关于这方面新增工具的应用。
扩展标记语言XML是一种简单的数据存储语言,使用一系列简单的标记描述数据,而这些标记可以用方便的方式建立。XML的简单使其易于在任何应用程序中读写数据,这使XML很快成为数据交换的唯一公共语言,可以说,“没有XML,就没有编程的未来”。
XML主要应用在以下几个方面:
1. 设计标记语言,如CML,MathML, WML等。
<web></web>
注意别大小写的,所以标记的大小写也必须相同。
节点标记中可以包含属性,比如:
<web type=”Homepage”></web>
以上只是对XML文档的简单描述,如何使用文档中包含的信息,XML标准体系中有其他的配套标准。
代码中Web节点包含属性Type,其值为Homepage.

VB.NET与XML的实例操作

VB.NET与XML的实例操作

与XML的实例操作再建⽴项⽬的⽂件夹的bin⽂件夹下 '创建两个⽂件 '⼀个是"myxml.xml" '⼀个是"myxml.mdb" '这⾥⾯有⼀个表"users"三个字段名"nameid","age","faverity" '再转到图形界⾯ '单击"⼯具箱"的"数据"把"OleDbConnection"," OleDbComman","DataSet","OleDbDataAdapter" '拉⼊窗体界⾯ '依次对这⼏个控件进⾏操作 '我的⽂件夹是D:\vbproject\WindowsApplication1 'D:\vbproject\WindowsApplication1/bin/myxml.xml 'D:\vbproject\WindowsApplication1/bin/myxml.mdb //======================准备结束============== (1)⾸先在机⼦上要有.Net FrameWork 打开依次展开:⽂件-新建-项⽬; 再选择VISUAL-BASIC-项⽬-Windows应⽤程序 这就是所需要⼀个⼩界⾯ 现在⼀步步的来写代码,完成它的功能 ⾸先来完成添加功能: 我们⽬标是:通过这三个⽂本框(姓名,年龄,爱好)来添加到数据库中。

然后再把这个数据库的表保存成XML格式 双击"添加"按钮 在⾥⾯写下以下这些代:(VB写的语⾔,不是C#) If TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "" Then '在三个⽂本框都不为空时,执⾏以下操作, '否则出错 Dim strsel As String strsel = "select * from users where nameid='" & TextBox1.Text & "'" '建⽴⼀个查询字符串,看要要添加的姓名,是否已在数据中存在,如果不存在就可以添加 OleDbCommand1 = New OleDbCommand mandText = strsel Me.OleDbCommand1.Connection = OleDbConnection1 OleDbConnection1.Open() Try '进⾏异常处理 Dim reader As OleDbDataReader = OleDbCommand1.ExecuteReader() If reader.Read() Then '通过DataReader来读取,如果读得到,表明数据在有这个姓名存在,不添加; ListBox1.Items.Add("已经有该记录!") Else reader.Close() '要对数据库进⾏操作,⾸先把DataReader关掉; Dim insert As String insert = "insert into users(nameid,age,faverity) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')" '建⽴⼀个插⼊字符串 OleDbCommand1 = New OleDbCommand mandText = insert Me.OleDbCommand1.Connection = Me.OleDbConnection1 Me.OleDbCommand1.ExecuteNonQuery() ListBox1.Items.Add("添加成功!!") '以下是把数据库的数据保存为XML格式 DataSet1 = New DataSet OleDbDataAdapter1 = New OleDbDataAdapter("select * from users", OleDbConnection1) OleDbDataAdapter1.Fill(DataSet1, "users") DataSet1.WriteXml("myxml.xml") End If Catch ex As Exception ListBox1.Items.Add("Errors!") End Try OleDbConnection1.Close() Else MessageBox.Show("请输⼊完整!!") End If //==================接下来是对数据库进⾏查询=================== '双击"查找"按钮 '写⼊以下代码 If TextBox4.Text <> "" Then '还是和上⾯⼀样如果⽂本框为空,就不执⾏,如果不为空,就执⾏下⾯的操作 ListBox1.Items.Clear() '⾸先把listBox清空 Dim searchtext As String searchtext = TextBox4.Text OleDbConnection1.Open() Dim selstring As String selstring = "select * from users where nameid like '%" & searchtext & "%'" ' 建⽴查询字符串,可以⽀持模糊查询 OleDbCommand1 = New OleDbCommand mandText = selstring Me.OleDbCommand1.Connection = OleDbConnection1 '以下⼏句是显⽰匹配的条数 DataSet1 = New DataSet OleDbDataAdapter1 = New OleDbDataAdapter(selstring, OleDbConnection1) OleDbDataAdapter1.Fill(DataSet1, "users") ListBox1.Items.Add("共有" & DataSet1.Tables("users").Rows.Count & "条匹配的记录") ListBox1.Items.Add("-------------------------------------------------------------") Try '进⾏异常处理 Dim cmdreader As OleDbDataReader = OleDbCommand1.ExecuteReader() While cmdreader.Read '注意这⾥要⽤while '不然就⽆法进⾏循环,就只能进⾏⼀次查询 ListBox1.Items.Add(cmdreader("nameid").ToString()) ListBox1.Items.Add(cmdreader("age").ToString()) ListBox1.Items.Add(cmdreader("faverity").ToString()) ListBox1.Items.Add("----------------------------------") End While cmdreader.Close() OleDbConnection1.Close() Catch ex As Exception ListBox1.Items.Add("Errors") End Try Else End If //================再把来XML⽂档,以XML形式显⽰在ListBox⾥⾯ 双击"XML⽂档" 写进下⾯这些代码: ListBox1.Items.Clear() ' 清空listBox Dim xtr As XmlTextReader = New XmlTextReader("myxml.xml") '创建成⼀个XmlTextReader读取"myxml.xml"⽂档 While xtr.Read Select Case (xtr.NodeType) ' 咱们⽤select case 形式来选择xml节点类型 Case XmlNodeType.XmlDeclaration '先从ListBox⾥写进xml声明=====xmldeclaration ListBox1.Items.Add("<?xml version='1.0' encoding='gb2312'?>") '再依次显⽰节点的名称,值 '包括根节点 Case XmlNodeType.Element ListBox1.Items.Add("<" & & ">") Case XmlNodeType.Text ListBox1.Items.Add(xtr.Value) Case XmlNodeType.EndElement ListBox1.Items.Add("</" & & ">") End Select End While xtr.Close() '关闭xmlTextReader //========再把数据库中所有数据显⽰在ListBox中======== '双击"查看全部"按钮 '写⼊下⾯的⼀些代码: ListBox1.Items.Clear() '这些代码⼤家应该可以看得懂了 OleDbConnection1.Open() Dim selall As String selall = "select * from users" OleDbCommand1 = New OleDbCommand mandText = selall Me.OleDbCommand1.Connection = OleDbConnection1 Try Dim creader As OleDbDataReader = OleDbCommand1.ExecuteReader() While creader.Read ListBox1.Items.Add("name: " & creader("nameid").ToString() & "; age :" & creader("age").ToString() & "; faverity :" & creader("faverity").ToString()) End While creader.Close() Catch ex As Exception ListBox1.Items.Add("Errors") End Try OleDbConnection1.Close() //==========================再来进完成删除按钮================= '双击"删除"按钮 '写⼊以下的代码 If TextBox4.Text <> "" Then '如果不为空,进⾏以下操作 ListBox1.Items.Clear() '先清空ListBox OleDbConnection1.Open() ' 建⽴连接 Dim delstring As String delstring = TextBox4.Text Dim delsel As String delsel = "select * from users where nameid='" & delstring & "'" '创建查询字符串 OleDbCommand1 = New OleDbCommand mandText = delsel Me.OleDbCommand1.Connection = OleDbConnection1 Try Dim selreader As OleDbDataReader = OleDbCommand1.ExecuteReader() If Not selreader.Read Then '假如读不到,就表明数据库⽆此数据,⽆法进⾏删除操作 MessageBox.Show("数据库中⽆该记录!") Else selreader.Close() '要对数据进⾏操作,必须⾸把DataReader关掉 Dim delrecord As String delrecord = "delete * from users where nameid='" & delstring & "'" '建⽴删除字符串sql语句,以上都是 OleDbCommand1 = New OleDbCommand mandText = delrecord Me.OleDbCommand1.Connection = OleDbConnection1 Me.OleDbCommand1.ExecuteNonQuery() MessageBox.Show("删除成功!!") '再把进⾏删除操作的数据库,再次把数据库中数据保存成XML⽂档 DataSet1 = New DataSet OleDbDataAdapter1 = New OleDbDataAdapter("select * from users", OleDbConnection1) OleDbDataAdapter1.Fill(DataSet1, "users") DataSet1.WriteXml("myxml.xml") End If Catch ex As Exception MessageBox.Show(ex.Message) Finally OleDbConnection1.Close() End Try Else MessageBox.Show("请输⼊你想删除的记录!") End If //======================= 重设按钮===== TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" ListBox1.Items.Clear() //============================关闭=============== me.Close() '好了这个⼩软件完成了,有问题的话留⾔ '本程序在.net framework 2003创建 '已经进⾏过测试,完全可以运⾏。

.Net读取配置文件xml

.Net读取配置文件xml

.Net读取配置⽂件xml直接解析XML⽂件在直接读取⽂件的时候由于⼿动getAttribute很⿇烦,⽽且容易出错,attribute可以参考log4net的⽅式,全部做成宏定义:使⽤.Net提供的的⽅式(ConfigurationManager类,⽀持.Net Core 2)特别说明:using System.Configuration 之后可能还要⼿动勾选,如下图:使⽤.Net 提供的⽅法读取有时候会很⽅便,可以直接将配置信息填写在app.config ⽂件中例如下⾯的配置⽂件读取的时候:<?xml version="1.0" encoding="utf-8" ?><configuration><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup><appSettings><add key="name" value="kun"/><add key="name2" value="kun"/></appSettings><connectionStrings><add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" /> </connectionStrings></configuration>static void ReadAllSettings(){try{var appSettings = ConfigurationManager.AppSettings;if (appSettings.Count == 0){Console.WriteLine("AppSettings is empty.");}else{foreach (var key in appSettings.AllKeys.Where((key) => key == "name")){Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);}}}catch (ConfigurationErrorsException){Console.WriteLine("Error reading app settings");}}static void ReadSetting(string key){try{var appSettings = ConfigurationManager.AppSettings;string result = appSettings[key] ?? "Not Found";Console.WriteLine(result);}catch (ConfigurationErrorsException){Console.WriteLine("Error reading app settings");}}读取数据库连接信息也可以只⽤⼀句代码:var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;对于这种简单key/Value⽅式的配置,使⽤ConfigurationManager类还是很⽅便的。

xml配置操作指引(XML文件配置指引及例程)

xml配置操作指引(XML文件配置指引及例程)

XML文件配置指引及例程一文档用途本文档主要用于指引工程服务人员如何通过配置VexTuner6.3安装包内的XML文件来实现虚拟屏矩形大小和标题文字随系统大小变化进行自适应更改。

阅读对象为工程服务人员,以及相关客户。

二操作例程假设现场有4*4的拼接墙,客户端PC(Tuner软件运行所处的PC)的分辨率为1280*1024.通过以下步骤,可以实现虚拟屏矩形大小和标题文字随配置文件的数据进行自适应。

1)通过Tuner软件添加该墙到墙资源列表2)双击打开该墙,此时可以看见安装包内新增了文件VCLConfig。

利用记事本软件打开该文件,可以看见以下内容:其中,LargeFontSize是大号字体,20是默认的大号字体的字号,可以进行任意修改。

NormalFontSize是正常字体,默认字号是15,SmallFontSize是小号字体,默认字号为10。

以上字号均可以进行手动修改,并进行保存。

WidthLarge:虚拟屏幕的宽度上限WidthSmall: 虚拟屏幕单屏的宽度下限,所有的屏幕宽度都不能低于此下限。

假设客户的PC是1280*1024分辨率,拼接墙大小为4行4列,作为例程。

以满屏计算,单屏的宽度为1280/4 = 320.1)WidthLarge值为80,320>80,那么虚拟屏文字采用大号字体(20)。

2)WidthLarge值为400,WidthSmall值为200,320>200且320<400, 虚拟屏文字采用正常字体(字号为15)3)WidthSmall值为400,320<400,虚拟屏文字采用小号字体(字号为10)4)WidthSmall既作为小号字体使用的下限值,同时,也是虚拟屏单屏最小宽度下限值。

假设系统是4*45大小,WidthSmall值为20,NormalFontSize值为10,SmallFontSize 值为8,那么得到的系统效果如下:。

VB如何操作INI文件方法详解

VB如何操作INI文件方法详解

VB如何操作INI文件方法详解INI文件是Windows系统中常用的配置文件格式,用于存储程序的配置信息。

在VB中,可以通过读取和写入INI文件来操作和修改配置信息。

下面是详细的操作INI文件的方法:1.引入API函数:在VB中,需要使用一些API函数来实现对INI文件的读取和写入操作,因此我们需要在代码中引入这些函数。

在模块中添加以下代码:```vbPrivate Declare Function GetPrivateProfileString Lib"kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As LongPrivate Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Long ```2.读取INI文件:读取INI文件的方法是使用GetPrivateProfileString函数,该函数有6个参数,分别对应应用程序名称、键名、默认值、返回的字符串、字符串长度和INI文件路径。

VB如何操作INI文件方法详解(3)

VB如何操作INI文件方法详解(3)

VB如何操作INI文件方法详解(3)DimDatabasenameAsStringDatabasename=GetIniS("数据库","职工","")IfDatabaseName=""ThenDatabaseName=InputBox("请输入数据库《职工》的目录"),App.Title)’也可通过"文件对话框"进行选择OnErrorResumeNextSetdb=OpenDatabas(DatabaseName)IfErr<>0ThenMsgBox"打开数据库失败!",MB-ICONSTOP,App.Title:GotoErrorProcessingElseSetIniS"数据库","职工",DatabaseNameEndIfOnErrorGoT o0……实例2:为了方便用户操作,有时需要保存用户界面的某些信息,例如窗口的高度和宽度等。

装载窗体时,从INI文件中读入窗体高度和宽度,卸载窗体时将窗体当前高度和宽度存入INI文件,代码如下: Sub Form1_Load()……Forml.Height=GetIniN("窗体1","高度",6000)Form1.Width=GetIniN("窗体1","高度",4500)EndSub……Sub Form1_Unload()……SetIniN"窗体1","高度",Me.HeightSetIniN"窗体1,"宽度",Me.Width ……End Sub。

VBNet中用XML替代INI配置功能的完整教程

VBNet中用XML替代INI配置功能的完整教程

中用XML替代INI配置功能的完整教程一、前言 (1)二、内容 (1)第一步:新建一个项目 (1)第二步:新建一个类 (1)第三步:写类代码 (1)第四步:调用 (5)第五步:测试 (6)三、尾声 (7)四、附:实例 (7)一、前言众所周知,xml文件很强大,从某种程度上说它完全替代ini也不为过,网上也有许多用编写xml文件的实例,但几乎找不到一个完整的xml替代ini的实例(也许是我太菜?),于是自己写了一个XML替代INI配置功能的完整类(当然,也可以改为模块),通过该类,创建、调用一个xml配置文件可以像VB6.0中配置INI文件一样简简单单,在Microsoft Visual Studio 2012中测试通过,好了,废话不多说,看文!二、内容第一步:新建一个项目首先,打开,新建一个项目,这不用说了吧^_^,咱现在是演示,一切命名都按默认的吧。

接着,新建一个类,还是默认命名(注意是类,不是模块)。

第三步:写类代码重点的代码来了,在类中写入以下代码:==================== 代码开始,勿复制本行 ====================Imports System.IOImports System.XmlPublic Class Class1'**************************************************'**模块名:XML_操作'**作用:完整替代 ini 的 xml 操作类'**创建人:灵魂的缠绵'**日期:2013-7-14'**************************************************#Region"变量声明区"Public Shared Root As String = .AssemblyName#End Region#Region"XML_创建"''' <summary>''' 【创建一个XML文档】''' 根据[XML文件路径]创建''' </summary>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Create(ByVal XmlPath As String)TryDim XmlWrite As New System.Xml.XmlTextWriter(XmlPath, System.Text.Encoding.GetEncoding("GB2312"))XmlWrite.Formatting = System.Xml.Formatting.Indented '自动缩进XmlWrite.WriteStartDocument(True) '开始一个文档自动编写版本并具有独立属性的XML声明XmlWrite.WriteStartElement(Root) '开始根元素XmlWrite.WriteEndElement() '关闭根元素XmlWrite.WriteEndDocument() '文档结束XmlWrite.Flush() '刷新XmlWrite.Close() '关闭Return TrueCatch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_读写_公共"''' <summary>''' 【XML_读写_公共】''' 根据[读写状态]判断[读][写]操作''' 有完整的[父、子节点]就改写[子节点]内容''' 否则创建,并根据[节点预设值]写[子节点]内容''' </summary>''' <param name="ReadWrite_Condition">读写状态</param>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeN">节点内容</param>''' <param name="XmlNodeY ">节点预设值</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_ReadWrite_Common(ByVal ReadWrite_Condition As Boolean, ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeN As String, ByVal XmlNodeY As String, ByVal XmlPath As String) As StringTryXML_ReadWrite_Common = NothingIf File.Exists(XmlPath) = False Then Call XML_Create(XmlPath) 'XML文件不存在就创建Dim VE As Boolean = Nothing'设置一个值用于判断是否[读取]的情况下[写入]Dim XmlDoc As New Xml.XmlDocument()XmlDoc.Load(XmlPath)Dim New_Root As Xml.XmlNode = XmlDoc.SelectSingleNode(Root)Dim New_XmlNodeF As Xml.XmlElement = NothingDim New_XmlNodeZ As Xml.XmlElement = NothingIf XmlNodeN Is Nothing Then XmlNodeN = XmlNodeYDim NodePathF As System.Xml.XmlNode = XmlDoc.SelectSingleNode(Root & "/" & XmlNodeF)If NodePathF Is Nothing Then'[父节点]不存在创建一个从[父节点]开始的完整的节点New_XmlNodeF = XmlDoc.CreateElement(XmlNodeF)New_XmlNodeZ = XmlDoc.CreateElement(XmlNodeZ)New_XmlNodeZ.InnerText = XmlNodeNNew_XmlNodeF.AppendChild(New_XmlNodeZ)New_Root.AppendChild(New_XmlNodeF)VE = TrueIf ReadWrite_Condition = True Then XML_ReadWrite_Common = XmlNodeYElse'[父节点]存在判断[子节点]是否存在Dim NodePathZ As System.Xml.XmlNode = XmlDoc.SelectSingleNode(Root & "/" & XmlNodeF & "/" & XmlNodeZ)If NodePathZ Is Nothing Then'[子节点]不存在创建一个从[子节点]开始的完整的节点New_XmlNodeZ = XmlDoc.CreateElement(XmlNodeZ)New_XmlNodeZ.InnerText = XmlNodeNNew_Root.SelectSingleNode(XmlNodeF).AppendChild(New_XmlNodeZ)If ReadWrite_Condition = True Then XML_ReadWrite_Common = XmlNodeYElse'[子节点]存在判断是读取还是写入If ReadWrite_Condition = True Then'当[读写状态]为[读]时If VE = True Then'在[读]时[写]入'读取的值为预设值XML_ReadWrite_Common = XmlNodeYElse'读取的值为[子节点]的值XML_ReadWrite_Common = New_Root.SelectSingleNode(XmlNodeF).SelectSingleNode(XmlNodeZ).InnerTextEnd IfElse'当[读写状态]为[写]时New_Root.SelectSingleNode(XmlNodeF).SelectSingleNode(XmlNodeZ).InnerText = XmlNodeNEnd IfEnd IfEnd IfxmlDoc.Save(XmlPath) '保存Catch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_读取"''' <summary>''' 【读取节点】''' 根据[父节点]和[子节点]定位''' 如果[子节点]不存在或无任何内容则根据[节点预设值]创建''' </summary>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeY">节点预设值</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Read(ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeY As String, ByVal XmlPath As String) As StringTryXML_Read = XML_ReadWrite_Common(True, XmlNodeF, XmlNodeZ, Nothing, XmlNodeY, XmlPath) Catch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_写入"''' <summary>''' 【写节点】''' 根据[父节点]和[子节点]定位''' 如果[子节点]不存在或无任何内容则根据[节点内容]创建,存在则根据[节点内容]覆盖原数据''' </summary>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeN">节点内容</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Write(ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeN As String, ByVal XmlPath As String)TryCall XML_ReadWrite_Common(False, XmlNodeF, XmlNodeZ, XmlNodeN, Nothing, XmlPath)Return TrueCatch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End RegionEnd Class==================== 代码结束,勿复制本行 ====================好了,这样类就写好了,为了便于审阅,单击左边的“-”将各功能代码折叠起来第四步:调用最后,可以调用了,调用前先做下准备工作:在窗口Form1内画4个文本框TextBox和2个按钮Button,布局如下图。

VB.NET读写XML配置文件

VB.NET读写XML配置文件

读写XML配置文件2009-04-08 16:58在WinCE中不能使用相对路径,必须获得配置文件的绝对路径WinCE中不支持System.IO.Directory.GetCurrentDirectory()Dim curDir As StringcurDir =System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecuti ngAssembly().GetName().CodeBase)Dim strFileName As String = curDir + "\config.xml"Dim fileInfo As New IO.FileInfo(strFileName)Dim xmlReader As System.Xml.XmlDocumentxmlReader = New Xml.XmlDocumentDim nodeList As Xml.XmlNodeListIf Not fileInfo.Exists ThenMessageBox.Show(strFileName + " does not exist") ElsexmlReader.Load(strFileName)nodeList =xmlReader.GetElementsByTagName("SystemName")MessageBox.Show(nodeList(0).Attributes(0).Valu e.ToString)End If---------------------------------------------------------------------------------------------------------------------------------Dim strFileName As String = "\Config.xml"Dim strFileFullPath As String =Directory.GetCurrentDirectory() + strFileNameDim strFile As FileInfo = New FileInfo(strFileFullPath)If strFile.Exists ThenConsole.WriteLine(strFileName + " Exists !") ElseConsole.WriteLine(strFileName + " Not Exists !") End IfDim xmlReader As Xml.XmlDocument = New Xml.XmlDocumentxmlReader.Load(strFileFullPath)Dim root As Xml.XmlNode = xmlReader.DocumentElementConsole.WriteLine(" Root = " + )Console.WriteLine(" Root ChildNotes is {0:D}",root.ChildNodes(1).Attributes(0).Value)root.ChildNodes(1).Attributes(0).Value = "123456789"xmlReader.Save(strFileFullPath)配置文件config.xml和程序放在同一个目录下,具体数据如下:<DMConfig><TSServer value="abcdefg" /><SystemName value="444444444444444" /><LogsPath value="2222222222222222" /><USBStickName value="33333333333333" /><USBSleepTimer value="25" /><IntroFilePath value="fffffffffffffff" /><AppFilePath value="ddddddddddddddd" /></DMConfig>。

VB和VB.NET中的XML操作(5)

VB和VB.NET中的XML操作(5)

VB和中的XML操作(5)3. 数据集的InferXmlSchema方法根据传递给它的XML数据的结构派生出数据集架构。

InferXmlSchema与上一节介绍的ReadXmlSchema方法的输入源相同。

另外,InferXMLSchema方法接受表示命名空间的字符串数组,这个空间在生成数据集架构时应被忽略。

Dim newDS As New System.Data.DataSet()Dim nsStr()As stringnewDS.InferXmlSchema("dataOnly.xml",nsStr))Me.daCategories.Fill(newDS.Tables("Categories"))Me.daProducts.Fill(newDS.Tables(Products"))newDS.Relations.Add("CategoriesProducts", _newDS.Tables("Categories").Columns("CategoryID"), _newDS.Tables("Products").Columns("CategoryID"))前两行代码声明了数据集和String数组变量,第3行将结果传递到InferXmlSchema方法中。

接下来的代码给新数据集添加并填充了新的数据关系,然后SetBindings函数将XML窗体控件绑定到数据集上。

4.WriteXmlSchema方法将数据集架构(包括表、列和约束)写到指定输出中。

这个方法和其他XML方法一样,都接受相同的输出参数。

Me.dsMaster1.WriteXmlSchema("testSchema.xsd")Messagebox.Show("Finished","WriteXmlSchema")5. 与ReadXml类似,数据集的WriteXml方法也可将XML数据或可选的数据集架构信息写到指定输出中。

vbnet读取xml的方法

vbnet读取xml的方法

vbnet读取xml的方法【最新版3篇】目录(篇1)I.vbnet读取xml的方法概述1.vbnet是一种面向对象的编程语言,可用于开发Windows平台下的应用程序。

2.xml是一种标记语言,用于描述数据结构和内容。

3.vbnet读取xml的方法可以用于从xml文件中获取数据,并将其转换为可读的数据结构。

II.vbnet读取xml的方法详细说明1.使用vbnet的XmlDocument类读取xml文件。

2.XmlDocument类提供了许多方法,可用于解析和操作xml文件。

3.使用XmlDocument类的Load方法加载xml文件,并将其解析为一个XmlDocument对象。

4.使用XmlDocument对象的SelectNodes方法,可以获取xml文件中指定标签下的所有节点。

5.使用XmlDocument对象的SelectSingleNode方法,可以获取xml 文件中指定标签下的第一个节点。

6.使用XmlDocument对象的ReadXml方法,可以将xml文件中的数据读取为一个字符串。

7.使用XmlDocument对象的WriteXml方法,可以将数据写入到xml 文件中。

正文(篇1)vbnet是一种面向对象的编程语言,可用于开发Windows平台下的应用程序。

xml是一种标记语言,用于描述数据结构和内容。

vbnet读取xml 的方法可以用于从xml文件中获取数据,并将其转换为可读的数据结构。

以下是vbnet读取xml的方法的详细说明。

使用vbnet的XmlDocument类读取xml文件。

XmlDocument类提供了许多方法,可用于解析和操作xml文件。

使用XmlDocument类的Load方法加载xml文件,并将其解析为一个XmlDocument对象。

使用XmlDocument 对象的SelectNodes方法,可以获取xml文件中指定标签下的所有节点。

使用XmlDocument对象的SelectSingleNode方法,可以获取xml文件中指定标签下的第一个节点。

VB.NET简单读写XML配置文件

VB.NET简单读写XML配置文件

Public Class Form1Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System. EventArgs) Handles Button2.ClickDim path As String = "d:\cong.XML"'写入XML失败,则先初始化,后写入If WriteXML(TextBox1.Text, TextBox2.Text, path) = False ThenResetXML(path)WriteXML(TextBox1.Text, TextBox2.Text, path)End IfEnd SubEnd ClassImports System.XmlModule Module1Public Function WriteXML(ByVal nameStr As String, ByVal valueStr As String, ByVal path As String) As BooleanTryDim doc As New XmlDocumentDim RootNode As XmlElementDim mBound, i As IntegerDim isExit As Boolean = Falsedoc.Load(path)'循环体遍历子节点RootNode = doc.DocumentElementmBound = RootNode.ChildNodes.Count - 1For i = 0 To mBoundIf RootNode.ChildNodes(i).Name = nameStr ThenRootNode.ChildNodes(i).InnerText = valueStrisExit = TrueExit ForEnd IfNext'如果修改失败,则创建节点If isExit = False ThenDim xn As XmlNode = doc.CreateNode(XmlNodeType.Ele ment, nameStr, "")RootNode.AppendChild(xn)xn.InnerText = valueStrEnd Ifdoc.Save(path)Return TrueCatch ex As ExceptionReturn False '如果XML文件遭到破坏,则返回False End TryEnd FunctionPublic Function GetXML(ByVal nameStr As String, ByVal faultStr As String, ByVal path As String) As String'节点或XML不存在都会返回faultStrTryDim valueStr As String = faultStrDim xtr As XmlTextReader = New XmlTextReader(path)While xtr.ReadIf = nameStr ThenvalueStr = xtr.ReadStringExit WhileEnd IfEnd Whilextr.Close()Return valueStrCatch ex As ExceptionReturn faultStrEnd TryEnd FunctionPublic Function ResetXML(ByVal path As String) As BooleanTryDim xmlInit As StringxmlInit = "<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "gb2312" & Chr(34) & "?>" & vbCrLf _& "<config>" & vbCrLf _& "</config>"puter.FileSystem.WriteAllText(path, xmlInit, False, S ystem.Text.Encoding.Default)Return TrueCatch ex As ExceptionReturn FalseEnd TryEnd FunctionEnd Module<?xml version="1.0" encoding="gb2312"?><config><hostsq>698</hostsq><hosts>258</hosts><price>369</price></config>。

利用vb操作xml数据(Using VB to operate XML data)

利用vb操作xml数据(Using VB to operate XML data)

利用vb操作xml数据(Using VB to operate XML data)What is XML?The extensible markup language XML is a simple data storage language, using a series of simple tags to describe data, and these markers can be used to establish a convenient way, although the XML space to occupy more space than the binary data, but XML is extremely simple and easy to master and use.XML and Access, Oracle and SQL Server database, the database provides the data storage and analysis capabilities, more powerful such as data indexing, sorting, searching, consistency, XML is only the display of data. In fact, the biggest difference between XML and other forms of data is that he is extremely simple. This is a look a little petty advantages, but it is in this respect that XML out of the ordinary.Simple XML to make it easy to read and write data in any application, the XML soon became the only common language of data exchange, although different applications also support other data exchange format, but soon they will support XML, it means that the program can be more easily with Windows, Mac OS Linux, and other platforms combined with the information, and then can easily load XML data into the program and his analysis, and XML format output results.Advantages of XMLWe talked about XML longer than the exchange of data between different applications, the XML file is to facilitate the construction of a small database, not long ago, the use of INIfile storage software configuration information, user preferences and other information, then Microsoft introduced the system registry, then Microsoft told we should not use the INI file, since then Visual Basic of the INI file support weakened. Unfortunately, the registry has several fatal drawbacks: it is not a simple text file to read and write, may become large and slow, if the registry is somehow there is a problem, it may cause system crashes.The configuration information in the XML file to avoid these problems, even the XML file can be set to a file sharing in different computer users can share data, which is incomparable to the registry.In the that is called the next generation ASP, you can use XML directly in the WEB page. You can bind data directly and automatically display using the data bound controls.Of course, you can not choose XML, the use of text files, registry, database, you can complete the task XML can complete, XML is just another tool you store and restore data.A brief introduction to XML grammarThe XML syntax is very simple, XML document consists of nodes, the use of open and close nodes in the format and description tags, HTML tags are very similar, the biggest difference between them is free to define the tag name XML. For example, the following tag describes a telephone number:< Phone > 987-654-3210 < /Phone >But no statement can use the tag name.The start and end tags must be the same, and the XML is case sensitive, so the markup must be the same. For example, in the above example, the beginning of < Phone > mark must end with < /Phone > mark, but not < /phone > or < /PHONE >Node tags can contain attributes, such as the Phone node in the code below contains the attribute Type, whose value is WorkFax:< Phone Type= "WorkFax" > 987-654-3210 < Phone >If you do not want to contain a value in the node, then do not need to mark the end, with a slash in the back to mark the beginning of the end node, in the following example, the Number attribute of the Phone tag is stored in a telephone number, there is no need for an end tag:< Phone Type= "WorkFax" Number= "987-654-3210" / >The structure of a XML document is a tree hierarchy. The document must have a unique root node,The root node contains all the other nodes. Let's give you a more complete example:< Addresses >< Entry Type= "Personal" >< FirstName > Andy < /FirstName >< LastName > Fickle < /LastName >< Street > 1234 Programmer Place < /Street >< City > Bugsville < /City >< State > CO < /State >< Zip > 82379 < /Zip >< Phone Type= "Home" > 354-493-9489 < /Phone >< /Entry >< Entry Type= "Work" >< FirstName > Betty < /FirstName >< LastName > Masterson < /LastName >< Phone Type= "Work" > 937-878-4958 < /Phone >< Phone Type= "WorkFax" > 937-878-4900 < /Phone > < /Entry >...< /Addresses >Note that similar nodes do not need to contain the same information, such as the first Entry node contains address information and home telephone number, the second Entry node contains the Work and WorkFax phone number, but does not include the first Entry node contains information.XML toolsAs in the previous example, the XML syntax is you can make a XML parser in a very short time so simple that, fortunately you do not have to do so, because the XML tool can be run on various platforms, including the Visual Basic Windows can be installed.It is these L tools, not the XML itself, that make XML more powerful and complex. Different parsers allow you to load the entire XML document at any point or just load a node. On the contrary, XML Writer can create an XML document and a node at the same time.The DOM parser enables us to easily load, copy, sort, modify, and store XML files, traverse the nodes to obtain names or attributes, and sort the results. Although their functions are not really relational, databases are powerful, but these features of DOM are still very useful.XSD defines the format of XML documents, and the XSL extended style sheet defines how to convert XML documents into other file formats that can be browsed in WEB browsers, such as HTML files.These tools are actually more complex than XML itself, so allof the books explaining XML have taken a lot of space to explain these XML tools. But this is beyond the scope of this article, interested readers can refer to the relevant information.Visual provides a complete tool for using XML, XSL, and other XML tools. But without waiting for , Microsoft XML core services (MSXML) version 4 provides tools to load and store XML documents from Visual Basic6.0.Download the latest version of MSXML in/xml/default.asp and install it on the computer. In Visual Basic 6 Microsoft XML V4.0 used as references to other objects, first select the reference menu item in the Project menu, select Microsoft V4.0, click OK, after the completion of all you can now add the XML object in the VB application.Class DOMDocumentThe document object model (DOM) uses a series of corresponding objects to describe the hierarchical state of the XML document, and the DOMDocument class is a MSXML class that describes the DOM structure of the XML document.The DOMDocument class provides only a few useful properties and methods. The Load method loads a XML file, and the loadxml method adds the string as the XML data to the object. For example, the following code adds a small XML file to a document called xml_document.Dim xml_document As New DOMDocumentXml_document.loadXML _“<人>”vbcrlf和_“<FirstName>杆</名>”vbcrlf和_“<姓>斯蒂芬斯</姓>”vbcrlf和_“</人>”属性返回文档的DOMDocument的XML XML描述,可以显示这些返回值看看这些文档究竟是什么样子,也可以将它存储为一个文件,但这完全不必要,因为DOMDocument对象的救方法已经自动将他们存储了。

迅速掌握VB.NET读取INI文件操作方法

迅速掌握VB.NET读取INI文件操作方法

迅速掌握读取INI文件操作方法•迅速掌握读取INI文件操作方法读取INI文件的相关操作方法对于初学者来说应该还是比较容易掌握的。

我们可以通过本文介绍的具体代码编写来具体了解其中的操作技巧。

做为一款最新的开发平台,为开发人员带来了很大的帮助。

因为对XML前不了解,所以对XML方式来做配置文件我都不能很好的实现,但为了应行,只有先使用INI的文来记录了,也就沿用了VB6里的INI文读取方法。

o浅析中冒号的作用o Flash控制程序的操作技巧分享o 开发效率优越性评比o 实现接口相关操作方法详解o Socket编程实际操作方法介绍下面请看读取INI文件的相关代码示例:1.'声明INI配置文件读写API函数2.Private Declare Function GetPrivateProfileString()3.Function GetPrivateProfileString Lib "kernel32"4.Alias "GetPrivateProfileStringA" (ByVal5.lpApplicationName As String, ByVal lpKeyName As6.String, ByVal lpDefault As String, ByVal lpReturned7.String As String, ByVal nSize As Int32, ByVal8.lpFileName As String) As Int329.Private Declare Function WritePrivateProfileString()10.Function WritePrivateProfileString Lib "kernel32"11.Alias "WritePrivateProfileStringA" (ByVal12.lpApplicationName As String, ByVal lpKeyName As13.String, ByVal lpString As String, ByVal lpFileName14.As String) As Int3215.'定义读取配置文件函数16.Public Function GetINI()Function GetINI(ByVal17.Section As String, ByVal AppName As String, ByVal18.lpDefault As String, ByVal FileName As String)19.As String20.Dim Str As String = LSet(Str, 256)21.GetPrivateProfileString(Section, AppName,22.lpDefault, Str, Len(Str), FileName)23.Return Microsoft.VisualBasic.Left(Str, InStr24.(Str, Chr(0)) - 1)25.End Function26.'定义写入配置文件函数27.Public Function WriteINI()Function WriteINI28.(ByVal Section As String, ByVal AppName As29.String, ByVal lpDefault As String, ByVal30.FileName As String) As Long31.WriteINI = WritePrivateProfileString(Section,32.AppName, lpDefault, FileName)33.End Function34.Private Sub Form1_Load()Sub Form1_Load(ByVal35.sender As System.Object, ByVal e As System.36.EventArgs) Handles MyBase.Load37.Dim path As String38.path = Application.StartupPath + "\server.ini"39.TextBox1.Text = GetINI("Server", "IP", "", path)40.TextBox2.Text = GetINI("Server", "port", "", path)41.End Sub42.Private Sub Button1_Click()Sub Button1_Click43.(ByVal sender As System.Object, ByVal e As44.System.EventArgs) Handles Button1.Click45.Try46.Dim path As String47.path = Application.StartupPath + "\server.ini"48.WriteINI("Server", "IP", TextBox1.Text, path)49.WriteINI("Server", "port", TextBox2.T ext, path)50.MsgBox("配置设置已经成功")51.Me.Close()52.Catch ex As Exception53.MsgBox("错误")54.End Try55.End Sub读取INI文件的相关操作就为大家介绍到这里。

vb.net创建、修改、读取XML的方法

vb.net创建、修改、读取XML的方法

创建、修改、读取XML的方法''' <summary>''' 创建XML文件''' </summary>''' <param name="xmlFileName">要创建的XML文件名</param>''' <remarks></remarks>Private Sub createXML(ByVal xmlFileName As String)TryDim writer As New Xml.XmlTextWriter(Application.StartupPa th & "" & xmlFileName, System.Text.Encoding.GetEncoding("utf-8"))'使用自动缩进便于阅读writer.Formatting = Xml.Formatting.Indentedwriter.WriteRaw("<?xml version=""1.0"" encoding=""utf-8"" ?>")'书写根元素()writer.WriteStartElement("Config")'添加次级元素writer.WriteStartElement("DatabaseSetting")'添加子元素()writer.WriteElementString("DataSource", Me.cmbHostName. SelectedItem.ToString.Trim)'为Datasource添加一个属性为value,值为test 的属性'writer.WriteAttributeString("value","test")writer.WriteElementString("InitialCatalog", Me.cmbDatabase Name.SelectedItem.ToString.Trim)writer.WriteElementString("UserID", Me.txtUserName.T ext.Tri m)writer.WriteElementString("Password", Me.txtPassword.T ext. Trim)'关闭次级元素DatabaseSettingwriter.WriteEndElement()'添加次级元素StationSettingwriter.WriteStartElement("StationSetting")'添加子元素writer.WriteElementString("StoreID", Me.cmbStoreID.Selecte dItem.ToString.Trim)writer.WriteElementString("StationID", Me.cmbStationID.Sel ectedItem.ToString.Trim)'关闭次级元素StationSettingwriter.WriteEndElement()'关闭根元素writer.WriteFullEndElement()'将XML写入文件并关闭writerwriter.Close()Catch ex As ExceptionMsgBox(ex.Message & vbCrLf & ex.StackTrace)End TryEnd Sub''' <summary>''' 修改XML''' </summary>''' <param name="xmlFileName">要修改的XML文件名</param>''' <param name="rootName">XML文件中的根元素名称</param>''' <param name="elementNameArry">要修改的元素数组</param>''' <param name="innerTextArry">对应于要修改的元素数组的修改文本数组</param>''' <remarks></remarks>Public Sub modifXML(ByVal xmlFileName As String, ByVal ro otName As String, ByVal elementNameArry() As String, ByVal in nerTextArry() As String)If puter.FileSystem.FileExists(Application.StartupPat h.Trim & "" & xmlFileName) ThenDim doc As New Xml.XmlDocumentdoc.Load(Application.StartupPath.Trim & "" & xmlFileName) Dim list As Xml.XmlNodeList = doc.SelectSingleNode(rootN ame).ChildNodesFor Each xn As Xml.XmlNode In listDim xe As Xml.XmlElementxe = xnDim nls As Xml.XmlNodeList = xe.ChildNodesFor Each xn1 As Xml.XmlNode In nlsDim xe2 As Xml.XmlElementxe2 = xn1For i As Integer = 0 To elementNameArry.Length - 1If = elementNameArry(i) Thenxe2.InnerText = innerTextArry(i)End IfNextNextNextdoc.Save(Application.StartupPath.Trim & "" & xmlFileName) End IfEnd Sub''' <summary>''' 读取XML文件''' </summary>''' <param name="xmlFileName">要读取的XML文件名</param>''' <remarks></remarks>Private Sub readXMl(ByVal xmlFileName As String)TryIf puter.FileSystem.FileExists(Application.StartupPat h & "" & xmlFileName) ThenDim doc As New Xml.XmlDocumentdoc.Load(Application.StartupPath.Trim & "" & xmlFileName) Dim re As Xml.XmlNodeReader = New Xml.XmlNodeReader (doc)Dim tmpStr As String = ""Dim name As StringWhile re.ReadSelect Case re.NodeTypeCase Xml.XmlNodeType.Elementname = Case Xml.XmlNodeType.TextIf name.Equals("DataSource") ThentmpStr = tmpStr & "Data Source=" & re.ValueEnd IfIf name.Equals("InitialCatalog") ThentmpStr = tmpStr & ";Initial Catalog=" & re.ValueEnd IfIf name.Equals("UserID") ThentmpStr = tmpStr & ";User ID=" & re.ValueEnd IfIf name.Equals("Password") ThentmpStr = tmpStr & ";Password=" & re.Value End IfEnd SelectEnd WhileEnd IfCatch ex As ExceptionMsgBox(ex.Message & vbCrLf & ex.StackTrace) End TryEnd Sub。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

中用XML替代INI配置功能的完整教程一、前言 (1)二、内容 (1)第一步:新建一个项目 (1)第二步:新建一个类 (1)第三步:写类代码 (1)第四步:调用 (5)第五步:测试 (6)三、尾声 (7)四、附:实例 (7)一、前言众所周知,xml文件很强大,从某种程度上说它完全替代ini也不为过,网上也有许多用编写xml文件的实例,但几乎找不到一个完整的xml替代ini的实例(也许是我太菜?),于是自己写了一个XML替代INI配置功能的完整类(当然,也可以改为模块),通过该类,创建、调用一个xml配置文件可以像VB6.0中配置INI文件一样简简单单,在Microsoft Visual Studio 2012中测试通过,好了,废话不多说,看文!二、内容第一步:新建一个项目首先,打开,新建一个项目,这不用说了吧^_^,咱现在是演示,一切命名都按默认的吧。

第二步:新建一个类接着,新建一个类,还是默认命名(注意是类,不是模块)。

第三步:写类代码重点的代码来了,在类中写入以下代码:==================== 代码开始,勿复制本行 ====================Imports System.IOImports System.XmlPublic Class Class1'**************************************************'**模块名:XML_操作'**作用:完整替代 ini 的 xml 操作类'**创建人:灵魂的缠绵'**日期:2013-7-14'**************************************************#Region"变量声明区"Public Shared Root As String = .AssemblyName#End Region#Region"XML_创建"''' <summary>''' 【创建一个XML文档】''' 根据[XML文件路径]创建''' </summary>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Create(ByVal XmlPath As String)TryDim XmlWrite As New System.Xml.XmlTextWriter(XmlPath, System.Text.Encoding.GetEncoding("GB2312"))XmlWrite.Formatting = System.Xml.Formatting.Indented '自动缩进XmlWrite.WriteStartDocument(True) '开始一个文档自动编写版本并具有独立属性的XML声明XmlWrite.WriteStartElement(Root) '开始根元素XmlWrite.WriteEndElement() '关闭根元素XmlWrite.WriteEndDocument() '文档结束XmlWrite.Flush() '刷新XmlWrite.Close() '关闭Return TrueCatch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_读写_公共"''' <summary>''' 【XML_读写_公共】''' 根据[读写状态]判断[读][写]操作''' 有完整的[父、子节点]就改写[子节点]内容''' 否则创建,并根据[节点预设值]写[子节点]内容''' </summary>''' <param name="ReadWrite_Condition">读写状态</param>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeN">节点内容</param>''' <param name="XmlNodeY ">节点预设值</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_ReadWrite_Common(ByVal ReadWrite_Condition As Boolean, ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeN As String, ByVal XmlNodeY As String, ByVal XmlPath As String) As StringTryXML_ReadWrite_Common = NothingIf File.Exists(XmlPath) = False Then Call XML_Create(XmlPath) 'XML文件不存在就创建Dim VE As Boolean = Nothing'设置一个值用于判断是否[读取]的情况下[写入]Dim XmlDoc As New Xml.XmlDocument()XmlDoc.Load(XmlPath)Dim New_Root As Xml.XmlNode = XmlDoc.SelectSingleNode(Root)Dim New_XmlNodeF As Xml.XmlElement = NothingDim New_XmlNodeZ As Xml.XmlElement = NothingIf XmlNodeN Is Nothing Then XmlNodeN = XmlNodeYDim NodePathF As System.Xml.XmlNode = XmlDoc.SelectSingleNode(Root & "/" & XmlNodeF)If NodePathF Is Nothing Then'[父节点]不存在创建一个从[父节点]开始的完整的节点New_XmlNodeF = XmlDoc.CreateElement(XmlNodeF)New_XmlNodeZ = XmlDoc.CreateElement(XmlNodeZ)New_XmlNodeZ.InnerText = XmlNodeNNew_XmlNodeF.AppendChild(New_XmlNodeZ)New_Root.AppendChild(New_XmlNodeF)VE = TrueIf ReadWrite_Condition = True Then XML_ReadWrite_Common = XmlNodeYElse'[父节点]存在判断[子节点]是否存在Dim NodePathZ As System.Xml.XmlNode = XmlDoc.SelectSingleNode(Root & "/" & XmlNodeF & "/" & XmlNodeZ)If NodePathZ Is Nothing Then'[子节点]不存在创建一个从[子节点]开始的完整的节点New_XmlNodeZ = XmlDoc.CreateElement(XmlNodeZ)New_XmlNodeZ.InnerText = XmlNodeNNew_Root.SelectSingleNode(XmlNodeF).AppendChild(New_XmlNodeZ)If ReadWrite_Condition = True Then XML_ReadWrite_Common = XmlNodeYElse'[子节点]存在判断是读取还是写入If ReadWrite_Condition = True Then'当[读写状态]为[读]时If VE = True Then'在[读]时[写]入'读取的值为预设值XML_ReadWrite_Common = XmlNodeYElse'读取的值为[子节点]的值XML_ReadWrite_Common = New_Root.SelectSingleNode(XmlNodeF).SelectSingleNode(XmlNodeZ).InnerTextEnd IfElse'当[读写状态]为[写]时New_Root.SelectSingleNode(XmlNodeF).SelectSingleNode(XmlNodeZ).InnerText = XmlNodeNEnd IfEnd IfEnd IfxmlDoc.Save(XmlPath) '保存Catch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_读取"''' <summary>''' 【读取节点】''' 根据[父节点]和[子节点]定位''' 如果[子节点]不存在或无任何内容则根据[节点预设值]创建''' </summary>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeY">节点预设值</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Read(ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeY As String, ByVal XmlPath As String) As StringTryXML_Read = XML_ReadWrite_Common(True, XmlNodeF, XmlNodeZ, Nothing, XmlNodeY, XmlPath) Catch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End Region#Region"XML_写入"''' <summary>''' 【写节点】''' 根据[父节点]和[子节点]定位''' 如果[子节点]不存在或无任何内容则根据[节点内容]创建,存在则根据[节点内容]覆盖原数据''' </summary>''' <param name="XmlNodeF">父节点</param>''' <param name="XmlNodeZ">子节点</param>''' <param name="XmlNodeN">节点内容</param>''' <param name="XmlPath">XML文件路径</param>''' <remarks></remarks>Public Shared Function XML_Write(ByVal XmlNodeF As String, ByVal XmlNodeZ As String, ByVal XmlNodeNAs String, ByVal XmlPath As String)TryCall XML_ReadWrite_Common(False, XmlNodeF, XmlNodeZ, XmlNodeN, Nothing, XmlPath)Return TrueCatch ex As ExceptionReturn FalseMsgBox(Err.Description)End TryEnd Function#End RegionEnd Class==================== 代码结束,勿复制本行 ====================好了,这样类就写好了,为了便于审阅,单击左边的“-”将各功能代码折叠起来第四步:调用最后,可以调用了,调用前先做下准备工作:在窗口Form1内画4个文本框TextBox和2个按钮Button,布局如下图。

相关文档
最新文档