1

I've got an XML file which describes connections, i.e.

    <?xml version="1.0" encoding="utf-8"?>
    <connections>
      <connection name="Local server remote">
        <ip>192.168.0.7        </ip>
        <port>23        </port>
        <description>
          Remote controlling of that nice & neat box under the table.
        </description>
        </connection>
        <connection name="Far, far away server HTTP access">
          <ip>77.32.57.144        </ip>
          <port>8080        </port>
          <description>
            A legend tells of a far, far away country of Russia, and of a server somewhere inside this mysterious country.
          </description>
        </connection>
      </connections>

Is there an easy way to parse that XML file into an object of a class like:

    class Connection {
        public string Name;
        public string IP;
        public int Port;
        public string Description;
     }

?

  • I'd suggest you have a look at this StackOverflow answer: http://stackoverflow.com/questions/608110/is-it-possible-to-deserialize-xml-into-listt as it is doing exactly what you're trying to do. – Adrian Dec 31 '15 at 01:23

3 Answers3

2

You will have to create a wrapper type to contain the list of connections as it doesn't know what <connections> is, then the rest is taken care of by adding an XmlElement name to each field.

public static void Main(string[] args)
{
    var serializer = new XmlSerializer(typeof (ConnectionList));

    var connections = ((ConnectionList)serializer.Deserialize(new StreamReader("data.xml"))).Connections;
    foreach (var connection in connections)
    {
        Console.WriteLine(connection.IP);
    }
    Console.ReadLine();
}

[XmlRoot("connections")]
public class ConnectionList
{
    [XmlElement("connection")]
    public List<Connection> Connections { get; set; } = new List<Connection>();
}

[XmlType("connection")]
public class Connection
{
    [XmlElement("description")] public string Description;

    [XmlElement("ip")] public string IP;

    [XmlElement("name")] public string Name;

    [XmlElement("port")] public int Port;
}

Note: '&' in the XML is an invalid character and must be escaped as &amp;

Cyral
  • 13,999
  • 6
  • 50
  • 90
2

You could use Linq to XML to read this in:

var xmlDoc = XDocument.Load("XMLFile1.xml");
if(xmlDoc.Root != null)
{
    var connections = (xmlDoc.Root.Elements("connection").Select(e => new Connection
    {
        Description = (string) e.Element("description"),
        IP = (string) e.Element("ip"),
        Name = (string) e.Element("name"),
        Port = (int) e.Element("port")
    })).ToList();
}

Probably worth pointing out that your XML file contains an & character which will throw off the XML document load. I was able to run the above code by replacing the ampersand with &amp;

chijos
  • 101
  • 1
  • 4
1

Try this. Best method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<Connection> connections = doc.Descendants("connection").Select(x => new Connection(){
                Name = x.Attribute("name").Value,
                IP = x.Element("ip").Value,
                Port = int.Parse(x.Element("port").Value),
                Description = x.Element("description").Value,
            }).ToList();
        }
    }
    public class Connection
    {
        public string Name { get; set; }
        public string IP { get; set; }
        public int Port { get; set; }
        public string Description { get; set; }
    }
}
​
jdweng
  • 33,250
  • 2
  • 15
  • 20