7

I need to read a XML file from App_Data in MVC3 according to the action that the user it's accessing at the moment.

<xml>
  <actions>
    <item action="index">
      <add url="www.stackoverflow.com" description="This site it's for learning purpouses" />
    </item>
  </actions>
</xml>

What would be the best way of getting that <item> according to the action user it's accessing?

EDIT


Forgot to mention that the XML may only be accessed by 1 controller. So the filename it's [controller].xml

1 Answer 1

10

You could use a XDocument and the XPathSelectElement extension method to parse XML:

public ActionResult Index()
{
    string action = RouteData.GetRequiredString("action");
    string controller = RouteData.GetRequiredString("controller");
    string appDataPath = Server.MapPath("~/app_data");
    string file = Path.Combine(appDataPath, controller + ".xml");
    var xpath = "//item[@action='" + action + "']";
    var item = XDocument.Load(file).XPathSelectElement(xpath);
    if (item != null)
    {
        var add = item.Element("add");
        var url = add.Attribute("url").Value;
        var description = add.Attribute("description").Value;
    }
    ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hm nice answer, but I guess there isn't a magical native way c# mvc3 do this and deal with the xml as objects and properties.
@Guilherme Costa, of course that there is a magical way. All you have to do is to define a view model that matches the XML structure and then deserialize the XML back to this view model. You could use the XmlSerializer class for example.
Also, you could use the magical DataSet: DataSet mydata = new DataSet(); mydata.ReadXml(Server.MapPath("~/App_Data/sdn.xml"));
what is path? Tell please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.