using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Xml.Linq;
namespace
UsingXML
{
class
PersonObject
{
public
string
fname {
get
;
set
; }
public
string
lname {
get
;
set
; }
public
int
age {
get
;
set
; }
public
char
gender {
get
;
set
; }
public
PersonObject()
{
this
.fname =
null
;
this
.lname =
null
;
this
.age = 0;
this
.gender =
'0'
;
}
public
PersonObject(
string
f,
string
l,
int
a,
char
g)
{
this
.fname = f;
this
.lname = l;
this
.age = a;
this
.gender = g;
}
}
class
ReadAndLoad
{
public
static
XDocument XDoc;
static
void
Main(
string
[] args)
{
Console.Write(
"Current Local Path: "
);
Console.WriteLine(Environment.CurrentDirectory);
Console.Write(
"Path to file? > "
);
string
UserPath = Console.ReadLine();
try
{
Console.WriteLine(
"\nNow Loading: {0}\n"
, UserPath);
XDoc = XDocument.Load(@UserPath);
}
catch
(System.IO.FileNotFoundException)
{
Console.WriteLine(
"No file found!"
);
Environment.Exit(1);
}
catch
(System.ArgumentException)
{
Console.WriteLine(
"Invalid path detected!"
);
Environment.Exit(1);
}
catch
(Exception err)
{
Console.WriteLine(
"An Exception has been caught:"
);
Console.WriteLine(err);
Environment.Exit(1);
}
List<PersonObject> PersonList =
new
List<PersonObject>();
var
query =
from
xml
in
XDoc.Descendants(
"Person"
)
select
new
PersonObject
{
fname = (
string
)xml.Element(
"FirstName"
),
lname = (
string
)xml.Element(
"LastName"
),
age = (
int
)xml.Element(
"Age"
),
gender = ((
string
)xml.Element(
"Gender"
) ==
"M"
?
'M'
:
'F'
)
};
PersonList = query.ToList();
int
ListSize = PersonList.Count;
if
(ListSize == 0)
{
Console.WriteLine(
"File contains no PersonObjects.\n"
);
Environment.Exit(0);
}
else
if
(ListSize == 1)
Console.WriteLine(
"Contains 1 PersonObject:\n"
);
else
Console.WriteLine(
"Contains {0} PersonObjects:\n"
, ListSize);
for
(
int
i = 0; i < ListSize; i++)
{
Console.WriteLine(
" PersonObject {0}"
, i);
Console.WriteLine(
"------------------------------------------"
);
Console.WriteLine(
" First Name : {0}"
, PersonList[i].fname);
Console.WriteLine(
" Last Name : {0}"
, PersonList[i].lname);
Console.WriteLine(
" Age ...... : {0}"
, PersonList[i].age);
Console.WriteLine(
" Gender ... : {0}"
, PersonList[i].gender);
Console.Write(
"\n"
);
}
Environment.Exit(0);
}
}
}