Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to read this XML?

Tags:

c#

xml

What is a good way to read this XML? Or maybe I can structure the XML differently.

What I want is the process to be the main thing and then you could have any number of related process to follow.

  <Job>
    <Process>*something.exe</Process>
    <RelatedToProcess>*somethingelse.exe</RelatedToProcess>
    <RelatedToProcess>*OneMorething.exe</RelatedToProcess>
  </Job>

I am currently using a XmlNodeList and reading the innertext and then splitting the string on * but I know there has to be a better way.

like image 559
Maestro1024 Avatar asked Dec 01 '25 08:12

Maestro1024


2 Answers

I suggest you to use Linq To Xml. You can load your xml in XDocument and then access each separate XElement by name or path.

like image 96
Andrew Bezzub Avatar answered Dec 04 '25 00:12

Andrew Bezzub


Try this console app:

class Program
{
    public class Job
    {
        public string Process { get; set; }
        public IList<string> RelatedProcesses { get; set; }
    }
    static void Main(string[] args)
    {
        var xml = "<Job>" +
                    "<Process>*something.exe</Process>" +
                        "<RelatedToProcess>*somethingelse.exe</RelatedToProcess>" +
                        "<RelatedToProcess>*OneMorething.exe</RelatedToProcess>" +
                      "</Job>";
        var jobXml = XDocument.Parse(xml);

        var jobs = from j in jobXml.Descendants("Job")
                    select new Job
                    {
                        Process = j.Element("Process").Value,
                        RelatedProcesses = (from r in j.Descendants("RelatedToProcess")
                                            select r.Value).ToList()
                    };

        foreach (var t in jobs)
        {
            Console.WriteLine(t.Process);
            foreach (var relatedProcess in t.RelatedProcesses)
            {
                Console.WriteLine(relatedProcess);
            }
        }

        Console.Read();

    }
}
like image 38
Chris Conway Avatar answered Dec 03 '25 22:12

Chris Conway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!