Just wanted to get values from XML file of an particular attribute to store in array.
So far I did this, but it didn’t make out.
C# Code
string[] name;
int n = 0;
using (XmlTextReader AReader = new XmlTextReader(Environment.CurrentDirectory + "\\Account.xml"))
{
while (AReader.Read())
{
AReader.ReadToFollowing("Account");
AReader.MoveToContent();
if (AReader.NodeType == XmlNodeType.Element && AReader.Name == "Account")
{
name[n] = AReader.GetAttribute("Name");
n++;
}
}
}
XML File
<?xml version="1.0"?>
<ArrayOfAccount>
<Account Name="John" Sex="Male" Age="28" />
<Account Name="Ram" Sex="Male" Age="22" />
</ArrayOfPatchConfig>
What output I need is
name[0]="John"
name[1]="Ram"
and So on…
I think this is enough to get an idea.
>Solution :
You want a List<T>, not an array. Arrays have a fixed size, which must be known beforehand, while lists can grow, making them ideal for this kind of application.
So, first off, create a new list:
var name = new List<string>();
// no need for n, the list keeps track of its count
Then, add elements to it:
if (AReader.NodeType == XmlNodeType.Element && AReader.Name == "Account")
{
name.Add(AReader.GetAttribute("Name"));
}
And that’s it.