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
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.
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.
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;
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With