Gravy
Gravy

Reputation: 12445

Read an XML file and store as an object

I am new to C#, MVC4, ASP.NET, Entity Framework.

I have an XML file which I want to convert to a c# object.

How do I do this?

To give an idea of what I would like to do with the XML file: I wish to display certain parts of the xml file within a table in a view. I wish to be able to select parts of the data and send to a database.

At present, I have...

        public ViewResult Index()
    {
        string url = "......";
        var xml = XDocument.Load(url);

        return View(xml);
    }

My view model is: @model IEnumerable But I get an error on run saying:

The model item passed into the dictionary is of type 'System.Xml.Linq.XElement', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement]'.

Upvotes: 1

Views: 1671

Answers (1)

saluce
saluce

Reputation: 13360

There are a few different methods of dealing with XML in .NET. These include XML Serializer, which will turn an XML string into a properly designed object; using XPath, which allows you to designate by a series of node names the information you want; or using XmlReader, which allows you to read through and parse the XML.

EDIT: Going with Xlinq, you'd want to pass as a model either XElement or IEnumerable<XElement> to the view

@model XElement

or

@model IEnumerable<XElement>

Upvotes: 3

Related Questions