0

I am trying to parse a long string(It is really an xml file).

I am familiar with substring but I don't know how to iterate through this long string(xml file) and assign substrings of it into an array.

I am entirely sure that this is a simple problem but I am stumped.

user1769538
  • 85
  • 1
  • 2
  • 4

2 Answers2

1

Well if you want to parse a list of objects I recommend you to use LINQ TO XML.

Here this little sample:

First my XML file

<?xml version="1.0" encoding="utf-8" ?>
<People>
  <Person>
    <Name>Luis</Name>
    <LastName>Laurent</LastName>
    <Age>24</Age>
  </Person>
  <Person>
    <Name>Juan</Name>
    <LastName>Perez</LastName>
    <Age>24</Age>
  </Person>
  <Person>
    <Name>Karla</Name>
    <LastName>Gutierrez</LastName>
    <Age>24</Age>
  </Person>
</People>

Then my .Net C# code

namespace Demo.Stackoverflow
{
    using System;
    using System.Linq;
    using System.Xml.Linq;

    public class Person
    {
        public string Name { get; set; }  
        public string LastName { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReadXML();
            Console.ReadLine();
        }

        private static void ReadXML()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Resources\\File.xml";
            XDocument doc = XDocument.Load(path);

            var People = (from people in doc.Descendants("Person")
                            select new Person()
                            {
                                Name = null != people.Descendants("Name").FirstOrDefault() ?
                                         people.Descendants("Name").First().Value : string.Empty,

                                LastName = null != people.Descendants("LastName").FirstOrDefault() ?
                                         people.Descendants("LastName").First().Value : string.Empty,

                                Age = null != people.Descendants("Age").FirstOrDefault() ?
                                         Convert.ToInt32(people.Descendants("Age").First().Value) : 0
                            }).ToList();
        }
    }
}
luis_laurent
  • 784
  • 1
  • 12
  • 32
0

Another option is to deserialize the XML into a class. You can then make methods and properties to deal with the various logic needs.

James Nearn
  • 171
  • 12