0

I´ve got a class called "server" with all attributes. I want to fill in the data from each node/element into the class. The only way I know is foreach and than everytime a big switch-case. This can´t be the best way!

Here the XML-File:

<serverData  .....>
  <name>...</name>
  <number>...</number>
  <language>de</language>
  <timezone>...</timezone>
  <domain>...</domain>
  <version>...</version>
  ...
</serverData>

The XML-File is from an API and I get it with this lines:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(Request.request(URL));

And now I want do something like (no real code just an example):

Server server = new Server();
server.name = xmlDoc.node["name"].Value;
server.version = ...
...

Thank you for your solution.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
LenglBoy
  • 1,451
  • 1
  • 10
  • 24

1 Answers1

1

You can use LINQ to XML:

XDocument xDoc = XDocument.Parse(Request.request(URL));

Server server = new Server {
    name = xDoc.Root.Element("name").Value,
    number = int.Parse(xDoc.Root.Element("name").Value),
    language = xDoc.Root.Element("language").Value,
    timezone = xDoc.Root.Element("timezone").Value
    /* etc. */
};

Since you have a well-formatted XML file with a constant structure, you can also simply serialize it using XmlSerializer:

[Serializable]
[XmlRoot("serverData")]
public class ServerData
{
    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("number")]
    public int Number { get; set; }

    [XmlElement("language")]
    public string Language { get; set; }

    [XmlElement("timezone")]
    public string Timezone { get; set; }

    /* ... */
}

XmlSerializer xmlSerializer = new XmlSerializer(typeof(ServerData));

using (Stream s = GenerateStreamFromString(Request.request(URL)))
{
    xmlSerializer.Deserialize(s);
}

GenerateStreamFromString implementation can be found here.

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • The first part of your answer helped me a lot. Thank you for this. The other answer is very well, too. – LenglBoy Dec 03 '15 at 12:33