Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get xml Attributes to arrays c# Windows form

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading