VB.NET 读取写入XML文件

前端之家收集整理的这篇文章主要介绍了VB.NET 读取写入XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Public Class CSysXML
    Dim mXmlDoc As New System.Xml.XmlDocument
    Public XmlFile As String

    Public Sub New(ByVal File As String)
        MyClass.XmlFile = File
        MyClass.mXmlDoc.Load(MyClass.XmlFile)       '加载配置文件  
    End Sub

    '功能:取得元素值  
    '参数:node--节点       element--元素名          
    '返回:元素值   字符型  
    '             $--表示出错误  
    Public Function GetElement(ByVal node As String,ByVal element As String) As String
        On Error GoTo Err
        Dim mXmlNode As System.Xml.XmlNode = mXmlDoc.SelectSingleNode("//" + node)

        '读数据  
        Dim xmlNode As System.Xml.XmlNode = mXmlNode.SelectSingleNode(element)
        Return xmlNode.InnerText.ToString
Err:
        Return "$"
    End Function
    '  
    '功能:保存元素值  
    '参数:node--节点名称     element--元素名       val--值  
    '返回:True--保存成功     False--保存失败  
    Public Function SaveElement(ByVal node As String,ByVal element As String,ByVal val As String) As Boolean
        On Error GoTo err
        Dim mXmlNode As System.Xml.XmlNode = mXmlDoc.SelectSingleNode("//" + node)
        Dim xmlNodeNew As System.Xml.XmlNode

        xmlNodeNew = mXmlNode.SelectSingleNode(element)
        xmlNodeNew.InnerText = val
        mXmlDoc.Save(MyClass.XmlFile)
        Return True
err:
        Return False
    End Function
End Class

例如:

XML:

<?xml version="1.0" encoding="gb2312"?>
<SystemIP>
<IP>
<num>192.168.0.6</num>
</IP>
</SystemIP>

程序调用

Public Class Form1
    Dim xml As New CSysXML("IP.xml")
    Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click
        Dim str As String = xml.GetElement("IP","num")
        TextBox1.Text = str
    End Sub
End Class
原文链接:https://www.f2er.com/vb/257703.html

猜你在找的VB相关文章