Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a xml file in App_Data with .NET MVC3 Framework according to controller?

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

like image 814
Guilherme David da Costa Avatar asked Oct 14 '11 14:10

Guilherme David da Costa


People also ask

How do I read an XML file in dotnet core?

Read XML File using XMLDocument Then make use of the method SelectNodes to fetch all the nodes for <Employee> from the XML file into the XmlNodeList class. Once all the nodes from the XML file have been fetched then we loop through the nodes available in XmlNodeList and print the value for each node.

What is XML file in asp net?

Introduction to XML in .Net XML is a cross-platform, hardware and software independent, text based markup language, which enables you to store data in a structured format by using meaningful tags. XML stores structured data in XML documents that are similar to databases.


1 Answers

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;
    }
    ...
}
like image 175
Darin Dimitrov Avatar answered Sep 22 '22 02:09

Darin Dimitrov