Blankman
Blankman

Reputation: 267180

Loading xml into a xdoc, and then initializing an object

My object looks like:

public class Template
{
     public string Title {get;set;}
     public string Body {get;set;}
}

xml that is stored in /files/test.xml in a web application (at the root):

<nodes>
<template name="someKey">
  <node name="title">soem title</node>
  <node name="body">some body text here</node>
</template>
</nodes>

So I can load the document like:

XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/files/test.xml"));

Now how would I load the object from the xml? (say for the template with name = somekey

Upvotes: 0

Views: 157

Answers (3)

Gregoire
Gregoire

Reputation: 24872

var templates = doc.Elements("template")
.FirstOrDefault(template=>template.Attribute("name").Value.Equals("someKey")
.Select(template=>new Template
{
    Title =  template.Elements("node").FirstOrDefault(node=>node.Attribute("name").Value.Equals("title")).Value,
    Body = template.Elements("node").FirstOrDefault(node=>node.Attribute("name").Value.Equals("body")).Value
 });

Upvotes: 1

Oded
Oded

Reputation: 499172

If you want to go from XML file directly to object, you should utilize serialization (specifically with the XmlSerializer class).

That way, you don't need to create you custom solution for going from file to object.

Take a look at the examples on the XmlSerializer msdn page, lots of good stuff on how this works.

Upvotes: 0

NPayette
NPayette

Reputation: 179

You could build an XSD (Schema) for your XML and using the XSD.exe Tool you could generate the class in which your XML could be deserialized into it.

I'm not sure this is what you wanted but it definitly works :)

Upvotes: 0

Related Questions