Blaze

Back Again

 

INI的替代品--XML配置文件读取与保存

.Net中并没有提供INI读写的托管类库,如果使用INI必须调用非托管API。有一个NINI提供了托管类库。
今天我们来实现XML配置文件读取与保存
1.集合类
         首先我们需要一个集合类来保存键和键值。它必须同时提供键名和索引两种查找键值的办法。所以我们采用 System.Collections.Specialized.NameValueCollection 类。需要注意的是这个类的键值只能是String。

Imports System.Xml
Public Class Setting
    
Inherits System.Collections.Specialized.NameValueCollection
End Class


2.XML配置文件格式
       配置文件格式我们采用app.config的格式

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    
<appSettings>
        
<add key="key1" value="value1"/>
    
</appSettings>
</configuration>


3.XML配置文件的读取

  Sub LoadSetting(ByVal FilePath As String)
        
Dim Reader As XmlTextReader
        
Try
            Reader 
= New XmlTextReader(FilePath)
            Reader.WhitespaceHandling 
= WhitespaceHandling.None '忽略所用Whitespace
            Me.Clear() '清除现有所有数据
        Catch ex As Exception
            
MsgBox("找不到XML文件" + ex.ToString)
            
Exit Sub
        
End Try
        
Try
            
While Reader.Read
                
If Reader.Name = "add" Then
                    
Dim Key, Value As String
                    Reader.MoveToAttribute(
"key")
                    Key 
= Reader.Value
                    Reader.MoveToAttribute(
"value")
                    Value 
= Reader.Value
                    Me.
Set(Key, Value)
                    Reader.MoveToElement()
                
End If
            
End While
        
Catch ex As Exception
            
MsgBox("XML文件格式错误" + ex.ToString)
            
Exit Sub
        
Finally
            Reader.Close()
        
End Try
    
End Sub


3.XML配置文件的写入


    Sub SaveSetting(ByVal FilePath As String)
        
Dim Writer As New XmlTextWriter(FilePath, System.Text.Encoding.Default)
        Writer.WriteStartDocument() 
'写入XML头
        Dim I As Integer
    Writer.WriteStartElement(
"configuration")    
Writer.WriteStartElement(
"appSettings")
        
For I = 0 To Me.Count - 1
            Writer.WriteStartElement(
"add")
            Writer.WriteStartAttribute(
"key"String.Empty)
            Writer.WriteRaw(Me.GetKey(I))
            Writer.WriteEndAttribute()
            Writer.WriteStartAttribute(
"value"String.Empty)
            Writer.WriteRaw(Me.Item(I))
            Writer.WriteEndAttribute()
            Writer.WriteEndElement()
        
Next
        Writer.WriteEndElement()
        Writer.WriteEndElement()
        Writer.Flush()
        Writer.Close()
    
End Sub


BTW:   也许你要问这些功能有何用处,是的在full framework中纯粹多余。可是.Net CF........

posted on 2005-01-15 17:45  Blaze  阅读(5025)  评论(1编辑  收藏  举报

导航