I'm trying to learn to use xml files in my application. I want to do a simple read of an element, and optionally rewrite an element and get its value. I have an xml file that looks something like:
<?xml version="1.0" encoding="utf-16"?>
<PTH>
<Account>
<Username>aa</Username>
<Password>xx</Password>
<Email>xyz@xyz.com</Email>
<Role>Student</Role>
</Account>
<ChartName>
<Id>1</Id>
<Name>John Smith</Name>
<PlaceOfBirth>louisville, ky</PlaceOfBirth>
<BirthDate>1/1/70</BirthDate>
<TimeZone>Greenwich</TimeZone>
</ChartName>
<ChartName>
<Id>2</Id>
<Name>John Smith</Name>
<PlaceOfBirth>New York, NY</PlaceOfBirth>
<BirthDate>1/1/1980</BirthDate>
<TimeZone>Greenwich</TimeZone>
</ChartName>
<ChartName>
<Id>3</Id>
<Name>Jane Doe</Name>
<PlaceOfBirth>Los Angeles, Ca</PlaceOfBirth>
<BirthDate>1/1/1990</BirthDate>
<TimeZone>Greenwich</TimeZone>
</ChartName>
</PTH>
Where there will only be one Account element and multiple ChartName elements. The code I came up with is:
public class Account
{
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
...
XDocument xml = XDocument.Load(HttpContext.Current.Server.MapPath("~") + "\\App_Data\\" + username.Text.Trim());
XElement xEle = xml.Element("PTH");
var Accounts = (from Account in xml.Root.Elements("Account")
select new
{
Email = (string)Account.Element("Email").Value,
Role = (string)Account.Element("Role").Value
});
foreach (var Account in Accounts)
{
Session["Email"] = Account.Email;
Session["Role"] = Account.Role;
}
The code works, but seems to be a really, REALLY convoluted way just to read the values of an element. Also, I'm not quite sure how I can, say, rewrite just the email element value. Does anyone have a much simple way to read and/or rewrite an element value? It seems like it should be very basic, but it escapes me...