LenglBoy
LenglBoy

Reputation: 1451

Get data from a XML-Node by element-name

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.

Upvotes: 0

Views: 1807

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

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.

Upvotes: 1

Related Questions