c# - Parsing XML Files in .NET -
i'm trying decide on best way load in configuration settings. basically, have application several people log into, , once they've logged in, want load of settings (for example: colors, font sizes, personal records, etc.)
i thinking of using xml file because thought easy parse in .net, seems more difficult anticipated.
<programsettings> <database file="c:\database.mdb" /> </programsettings> <usersettings> <user key="user1"> <layout color="red" fontsize="5" /> <data file="c:\test1.txt" /> </user> <user key="user2"> <layout color="blue" fontsize="2" /> <data file="c:\test2.txt" /> </user> </usersettings>
note: reason of code not appearing, there major sections labeled "programsettings" , "usersettings." edit: whoever fixed me.
anyway, "user key" user's login name or something. then, nice able this:
string userlogin = "user1"; // returns red string color = myxmlfile["usersettings"][userlogin]["layout"]["color"]; // returns 5 string fontsize = myxmlfile["usersettings"][userlogin]["layout"]["fontsize"];
is possible? research i've done seems indicate need loop through each value. i'd load whole file, , access element directly.
it cool if edit values like:
myxmlfile["usersettings"][userlogin]["layout"]["fontsize"] = "green";
i think comfortable way of dealing xml files in c# using linq xml.
using (filestream lstream = new filestream("configurationsettings.xml", filemode.open, fileaccess.read)) { xelement lroot = xelement.load(lreader) string userlogin = "user1"; xelement user = lroot.element("usersettings").elements("user").where(x => x.attribute("key").value == userlogin).firstordefault(); if (user != null) { // returns red string color = user.element("layout").attribute("color").value; // returns 5 string fontsize = user.element("layout").attribute("fontsize").value; } }
Comments
Post a Comment