开发者

Loading xml into a xdoc, and then initializing an object

My object looks like:

public class Template
{
 开发者_StackOverflow社区    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


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
 });


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜