开发者

Parsing XML Files in .NET

开发者 https://www.devze.com 2023-01-28 08:53 出处:网络
I\'m trying to decide on the best way to load in some configuration settings.Basically, I have an application that several people will log into, and once they\'ve logged in, I want to load all of thei

I'm trying to decide on the best way to load in some configuration settings. Basically, I have an application that several people will log into, and once they've logged in, I want to load all of their settings (for example: colors, font sizes, personal records, etc.)

I was thinking of using an XML file to do this because I thought it would be fairly easy to parse in .NET, but it seems to be more difficult that I 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: For some reason some of the code is not appearing, but basically there are major sections labeled "ProgramSettings" and "UserSettings." Edit: Thanks whoever fixed that for me.

Anyway, what I would like to do is get the "user key" which will be the user's login name or something. Then, it would be nice to be able to do something like this:

String userLogin = "user1";

// returns red
String color = myXMLFile["UserSettings"][userLogin]["layout"]["color"];         

// returns 5
String fontSize = myXMLFile["UserSettings"][userLogin]["layout"]["fontsize"开发者_开发知识库];   

Is anything like this possible? All the research I've done seems to indicate that you need to loop through each value. I'd like to load the whole file, and access any element directly.

It would also be cool if you could edit the values like:

myXMLFile["UserSettings"][userLogin]["layout"]["fontsize"] = "green";


I would advise you to use the integrated configuration model, this will take all the work from you. You can find it in the projects settings under settings.

It has both user level (changeable) and application level (not changeable in code) as you want, you can use the data by accessing it via projectnamespace.Properties.Settings.

msdn (the link is for visual studio 2005, it applies for any further versions as well though).


Take a Look at XDocument if you are using .NET 3.5 or higher.

MSDN XDocument

You could do what you are trying to do as this:

XDocument Settings = new XDocument;
Settings = XDocument.Load("XmlFilePath");

//This Section Gets the Program Settings

XElement ProgramSettings = Settings.Element("ProgramSettings");
string DatabaseFile = ProgramSettings.Element("database").Attribute("file").Value.ToString();


//This section gets the logged in users Settings

XElement UserSettings = Settings.Element("UserSettings");

//Get Node For current USer

XElement CurrentUserSettings = UserSettings.Element(loggedInUserName);
string UserColor = CurrentUserSettings.Element("Layout").Attribute("color").Value.ToString();
string USerFontSize = CurrentUserSettings.Element("Layout").Attribute("font").Value.ToString();
string dataFile = CurrentUserSettings.Element("data").Attribute("file").Value.ToString();

That should work for you.


I think a fairly comfortable way of dealing with XML files in C# is using Linq to 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;
      }

}


I wouldnt say its an ideal approach and i cant remember the exact syntax off top of my head but you can use the System.Linq.Xml library, which is part of .net 3.5.

You would first of all load in your xml file which would be something like:

var xDoc = XDocument.Load("MyFile.xml");
var myElementValue = xDoc.Element("UserSettings")
                         .Element("userLogin")
                         .Element("layout")
                         .Element("fontsize")
                         .Value;

My syntax may not be 100% correct and really you should do some validation to make sure your nodes are all there before you read it all out, but I think that should do what you want. You may even be able to do an XPath to just go directly to the node... something like:

var xmlResult = xDoc.XPathSelectElement("UserSettings/UserLogin/Layout/Fontsize").Value;

Look for that namespace for more info, as this is as far as i know the new way to work with XML since .net 3.5.


Have a look at the System.Xml.XmlDocument class. Specifically the SelectSingleNode method, which will give you an XmlNode which has a Value property that you can write to.

0

精彩评论

暂无评论...
验证码 换一张
取 消