Home > front end >  Get xml Attributes to arrays c# Windows form
Get xml Attributes to arrays c# Windows form

Time:10-07

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" />
 </ArrayOfAccount>

What output I need is

name[0]="John"
name[1]="Ram"

and So on...

I think this is enough to get an idea.

CodePudding user response:

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.

CodePudding user response:

Here's the easy way to do what you want:

string[] name =
    XDocument
        .Load(Environment.CurrentDirectory   "\\Account.xml")
        .Root
        .Elements("Account")
        .Select(e => (string)e.Attribute("Name"))
        .ToArray();

CodePudding user response:

You can get using linq. By this no need to bother about size and you get string[] array.

Complete Code

 string myXML = @"<?xml version=""1.0""?>
                          <ArrayOfAccount>
                         <Account Name=""John"" Sex =""Male"" Age=""28""/>
                         <Account Name=""Ram"" Sex=""Male"" Age=""22""/>
                         </ArrayOfAccount>
                         ";

            XDocument xdoc = new XDocument();
            xdoc = XDocument.Parse(myXML);

            IEnumerable<string> names = (from account in
                                          xdoc.Descendants("Account")
                                        select account.Attribute("Name").Value).ToArray();

in Your case , it is file so

IEnumerable<string> names = (from account in
                                    XDocument.Load(@"yourPath")
                                              .Descendants("Account")
                                        select customers.Attribute("Name").Value).ToArray();

enter image description here

  • Related