C # read-write configuration file (XML file)

Source: Internet
Author: User

The. xml file format is as follows

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE dataaccess[]> <DataAccess> <appSettings> <add key= "StartTime" value= "9"/> <add "key=" Endtime "value=" 6 "/> </appSettings> </DataAccess>

C # Initialization

private static XmlDocument Xmliauconfig; Static ConfigManager () {xmliauconfig = new XmlDocument (); Xmlpath = assembly.getexecutingassembly (). CodeBase; Int32 i = xmlpath.lastindexof ("/"); Xmlpath = Xmlpath.remove (i); Xmlpath = Xmlpath + @ "/abc.xml"; Xmliauconfig.load (Xmlpath); }

Gets the value of a node

public static string GetValue (String key) {xmliauconfig.load (Xmlpath); String value; String path = @ "//dataaccess/appsettings/add[@key = '" + key + "']"; XmlNodeList Xmladds = xmliauconfig.selectnodes (path); if (Xmladds.count = = 1) {XmlElement xmladd = (XmlElement) xmladds[0]; value = Xmladd.getattribute ("value");} else {throw New Exception ("Iauconfig configuration Information set error: The key value is" + key + "element is not equal to 1"); return value; }

Modify a node for a value

public static void Savaconfig (String strkey, String strvalue) {XmlDocument xmldoc = new XmlDocument (); Xmldoc.load ("Abc.xml"); XmlNodeList list = Xmldoc.getelementsbytagname ("add"); for (int i = 0; i < list. Count; i++) {if (List[i]. Attributes[0]. Value = = strkey) {List[i]. ATTRIBUTES[1]. Value = strvalue; } StreamWriter Swriter = new StreamWriter ("Abc.xml"); XmlTextWriter XW = new XmlTextWriter (Swriter); Xw. formatting = formatting.indented; Xmldoc.writeto (XW); Xw. Close (); Swriter. Close (); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.