views:

29

answers:

3

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

A: 

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 :)

NPayette
A: 

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.

Oded
+1  A: 
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
 });
Gregoire
will this return an error if they are not found in the xml?
Blankman
@Blankman: yes. You can put a default value after the firstordefault calls to avoid these errors. Ex: .FirstOrDefault(template=>template.Attribute("name").Value.Equals("someKey")?? new XElement("Somekey")
Gregoire
very cool, thanks!
Blankman