xml文件操作

C#:
using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Xml;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.Data;

using System.Data.Sql;



namespace DataProcessing

{

    class Config

    {

        private static string path = Environment.CurrentDirectory + "//config.xml";



        #region 将配置信息写入配置文件

        public static bool writeConfig(string Server,string User,string Password)

        {

            try

            {

                FileInfo fileInfo = new FileInfo(path);

                if (!fileInfo.Exists)

                {

                    createConfigFile();

                }

                XmlDocument xmlDocument = new XmlDocument();

                xmlDocument.Load(fileInfo.FullName);



                foreach (XmlNode node in xmlDocument["configuration"]["appSettings"].ChildNodes)

                {

                    if (node.Name == "add")

                    {

                        if (node.Attributes["key"].Value == "Server")

                        {

                            node.Attributes["value"].Value =Server;

                        }

                        else if (node.Attributes["key"].Value == "User id")

                        {

                            node.Attributes["value"].Value =User;

                        }

                        else if (node.Attributes["key"].Value == "Password")

                        {

                            node.Attributes["value"].Value =Password;

                        }

                    }

                }

                xmlDocument.Save(fileInfo.FullName);

                return true;

            }

            catch (Exception er)

            {

                MessageBox.Show(er.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;

            }

        }

        #endregion



        #region 读取配置文件(根据key返回相应的value

        public static string readConfig(string key)

        {

            try

            {

                string value = "";

                FileInfo fileInfo = new FileInfo(path);

                if (!fileInfo.Exists)

                {

                    createConfigFile();

                }

                XmlDocument xmlDocument = new XmlDocument();

                xmlDocument.Load(fileInfo.FullName);



                foreach (XmlNode node in xmlDocument["configuration"]["appSettings"].ChildNodes)

                {

                    if (node.Name == "add")

                    {

                        if (node.Attributes["key"].Value == key)

                        {

                            value = node.Attributes["value"].Value;

                        }

                    }

                }

                return value;

            }

            catch (Exception er)

            {

                MessageBox.Show(er.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return null;

            }

        }

        #endregion



        #region 设置登录信息

        public static bool setLoginInfo(string LoginUser,string LoginPassword)

        {

            try

            {

                FileInfo fileInfo = new FileInfo(path);

                if (!fileInfo.Exists)

                {

                    createConfigFile();

                }

                XmlDocument xmlDocument = new XmlDocument();

                xmlDocument.Load(fileInfo.FullName);



                foreach (XmlNode node in xmlDocument["configuration"]["appSettings"].ChildNodes)

                {

                    if (node.Name == "add")

                    {

                        if (node.Attributes["key"].Value == "LoginUser")

                        {

                            node.Attributes["value"].Value = LoginUser;

                        }

                        else if (node.Attributes["key"].Value == "LoginPassword")

                        {

                            node.Attributes["value"].Value = Encryption.MD5(LoginPassword);

                        }

                    }

                }

                xmlDocument.Save(fileInfo.FullName);

                return true;

            }

            catch (Exception er)

            {

                MessageBox.Show(er.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;

            }

        }

        #endregion



        #region 获得连接字符串

        public static string getConnectionString(string DBName)

        {

            StringBuilder constr = new StringBuilder();

            constr.Append("server=");

            constr.Append(readConfig("Server"));

            if (DBName != string.Empty)

            {

                constr.Append(";database=");

                constr.Append(DBName);

            }

            constr.Append(";user id=");

            constr.Append(readConfig("User id"));

            constr.Append(";password=");

            constr.Append(readConfig("Password"));

            return constr.ToString();

        }

        #endregion



        #region 创建配置文件

        public static void createConfigFile()

        {

            try

            {

                FileInfo fileInfo = new FileInfo(path);

                if (!fileInfo.Exists)

                {

                    XmlTextWriter writer = new XmlTextWriter(path,Encoding.UTF8);

                    writer.Formatting = Formatting.Indented;

                    writer.WriteStartDocument();

                    writer.WriteStartElement("configuration");

                    writer.WriteStartElement("appSettings");



                    writer.WriteStartElement("add");

                    writer.WriteAttributeString("key", "Server");

                    writer.WriteAttributeString("value", "127.0.0.1");

                    writer.WriteEndElement();



                    writer.WriteStartElement("add");

                    writer.WriteAttributeString("key", "User id");

                    writer.WriteAttributeString("value", "sa");

                    writer.WriteEndElement();



                    writer.WriteStartElement("add");

                    writer.WriteAttributeString("key", "Password");

                    writer.WriteAttributeString("value", "");

                    writer.WriteEndElement();



                    writer.WriteStartElement("add");

                    writer.WriteAttributeString("key", "LoginUser");

                    writer.WriteAttributeString("value", "sa");

                    writer.WriteEndElement();



                    writer.WriteStartElement("add");

                    writer.WriteAttributeString("key", "LoginPassword");

                    writer.WriteAttributeString("value", "c12e01f2a13ff5587e1e9e4aedb8242d");

                    writer.WriteEndElement();



                    writer.WriteEndElement();

                    writer.WriteEndElement();

                    writer.WriteEndDocument();

                    writer.Flush();

                    writer.Close();

                }

            }

            catch (Exception er)

            {

                throw new Exception(er.Message);

            }

        }

        #endregion

    }

}



config.xml文件:
<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <appSettings>

    <add key="Server" value="serverurl" />

    <add key="User id" value="dbuser" />

    <add key="Password" value="password" />

    <add key="LoginUser" value="username" />

    <add key="LoginPassword" value="52ba8e68faf75a9771420d45fda64955" />

  </appSettings>

</configuration>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是一个 VB.NET 操作 XML 文件的示例: 1. 创建 XML 文件: ``` Dim xmlDoc As New XmlDocument() Dim xmlDeclaration As XmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing) xmlDoc.AppendChild(xmlDeclaration) Dim rootNode As XmlElement = xmlDoc.CreateElement("Root") xmlDoc.AppendChild(rootNode) xmlDoc.Save("test.xml") ``` 2. 读取 XML 文件: ``` Dim xmlDoc As New XmlDocument() xmlDoc.Load("test.xml") Dim rootNode As XmlElement = xmlDoc.DocumentElement For Each childNode As XmlNode In rootNode.ChildNodes Console.WriteLine(childNode.Name & ": " & childNode.InnerText) Next ``` 3. 修改 XML 文件: ``` Dim xmlDoc As New XmlDocument() xmlDoc.Load("test.xml") Dim rootNode As XmlElement = xmlDoc.DocumentElement For Each childNode As XmlNode In rootNode.ChildNodes If childNode.Name = "NodeName" Then childNode.InnerText = "New Value" End If Next xmlDoc.Save("test.xml") ``` 希望这些代码对你有所帮助。 ### 回答2: VB.net中操作XML文件常用的类是XmlDocument类和XmlNode类。下面是一个使用VB.net操作XML文件的示例。 ```vb.net Imports System.Xml Public Class XMLExample Public Sub ReadXMLFile(filePath As String) ' 创建一个XmlDocument对象 Dim xmlDoc As New XmlDocument() ' 加载XML文件 xmlDoc.Load(filePath) ' 获取根节点 Dim rootNode As XmlNode = xmlDoc.DocumentElement ' 遍历根节点下的所有子节点 For Each childNode As XmlNode In rootNode.ChildNodes ' 输出子节点的名称和内容 Console.WriteLine("节点名称: " & childNode.Name) Console.WriteLine("节点内容: " & childNode.InnerText) Next End Sub Public Sub WriteXMLFile(filePath As String) ' 创建一个XmlDocument对象 Dim xmlDoc As New XmlDocument() ' 创建根节点 Dim rootNode As XmlNode = xmlDoc.CreateElement("Books") ' 将根节点添加到XmlDocument对象中 xmlDoc.AppendChild(rootNode) ' 创建子节点 Dim bookNode As XmlNode = xmlDoc.CreateElement("Book") ' 创建子节点的属性 Dim attrib As XmlAttribute = xmlDoc.CreateAttribute("ISBN") attrib.Value = "978-7-121-32712-3" ' 将属性添加到子节点中 bookNode.Attributes.Append(attrib) ' 将子节点添加到根节点中 rootNode.AppendChild(bookNode) ' 创建子节点的子节点 Dim titleNode As XmlNode = xmlDoc.CreateElement("Title") titleNode.InnerText = "VB.net XML文件操作实例" ' 将子节点的子节点添加到子节点中 bookNode.AppendChild(titleNode) ' 保存XML文件 xmlDoc.Save(filePath) End Sub End Class ' 使用示例 Private Sub Main() Dim example As New XMLExample() Dim filePath As String = "example.xml" ' 写入XML文件 example.WriteXMLFile(filePath) ' 读取XML文件 example.ReadXMLFile(filePath) End Sub ``` 上述示例中,提供了读取XML文件和写入XML文件的两个方法。创建了一个XmlDocument对象来加载和操作XML文件。通过XmlDocument对象的方法和属性,可以方便地读取和修改XML文件的内容。读取XML文件时,通过遍历节点的方式获取节点的名称和内容。写入XML文件时,通过创建节点和属性的方式构建XML节点树,并将节点添加到XmlDocument对象中。最后使用XmlDocument对象的Save方法将XML文件保存到磁盘中。 ### 回答3: 在VB.net中,我们可以使用System.Xml命名空间下的类来进行XML文件操作。下面是一个XML文件操作的实例: 首先,我们需要在程序中引入System.Xml的命名空间,以便使用相应的类。可以在代码文件的顶部添加以下代码: ```vb Imports System.Xml ``` 接下来,我们需要创建一个XmlDocument对象来加载XML文件。假设我们有一个名为"example.xml"的XML文件,它的内容如下: ```xml <?xml version="1.0" encoding="UTF-8"?> <products> <product> <id>1</id> <name>Product1</name> <price>10.0</price> </product> <product> <id>2</id> <name>Product2</name> <price>20.0</price> </product> </products> ``` 我们可以使用以下代码来加载XML文件: ```vb Dim xmlDoc As New XmlDocument() xmlDoc.Load("example.xml") ``` 接下来,我们可以使用SelectNodes或SelectSingleNode方法来选择XML节点。例如,要选择所有的product节点,可以使用以下代码: ```vb Dim productNodes As XmlNodeList = xmlDoc.SelectNodes("/products/product") ``` 如果要选择某个具体的节点,可以使用SelectSingleNode方法,并传入XPath表达式。例如,要选择第一个product节点的name子节点,可以使用以下代码: ```vb Dim nameNode As XmlNode = xmlDoc.SelectSingleNode("/products/product[1]/name") ``` 要访问节点的内容,可以使用InnerText属性或Value属性。例如,要获取第一个product节点的name子节点的文本内容,可以使用以下代码: ```vb Dim name As String = nameNode.InnerText ``` 如果要修改节点的内容,可以直接修改节点的InnerText属性。例如,要将第一个product节点的name子节点的文本内容修改为"New Product",可以使用以下代码: ```vb nameNode.InnerText = "New Product" ``` 最后,我们需要保存修改后的XML文件。可以使用Save方法来保存XML文件。例如,要保存修改后的XML文件为"example_modified.xml",可以使用以下代码: ```vb xmlDoc.Save("example_modified.xml") ``` 以上就是一个简单的VB.net中操作XML文件的示例。通过使用System.Xml命名空间下的类,我们可以加载、选择、修改和保存XML文件中的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值