How to read xml document in MVC core (1.0.0)?

Ask Question:

I’m new to web programming and decided to switch from .net 4.5 to .net core.

My project has a static xml document in the following location:

wwwroot/Countries/en-GB.xml

How would one go about reading the xml file at the specified path? Eventually I will convert the data to a SelectList.

In .net 4.5 I used DataSet’s and HttpConext…MapPath to read the xml document which no longer works in core mvc.

Any advice is greatly welcome.


Answer:

adem caglin First of all don’t put your data source into wwwroot folder, because it is served publicly. Take a look at official docs:

The web root of your app is the directory in your project for public, static resources like css, js, and image files. The static files middleware will only serve files from the web root directory (and sub-directories) by default.

So move Countries folder in your project’s root folder.

To read xml data, you can use XmlSerializer. I will try to show how to read xml file:

First i assume you have xml content like below:

<?xml version="1.0" encoding="UTF-8" ?>
<Container>
  <Countries>
    <Country>
      <Code>Code1</Code>
      <Title>Title1</Title>
    </Country>

    <Country>
      <Code>Code2</Code>
      <Title>Title2</Title>
    </Country>
  </Countries>
</Container>

First describe types

public class Country
{
    public string Code { get; set; }
    public string Title { get; set; }
}
public class Container
{
    public Country[] Countries { get; set; }
}

After that create a service for xml deserialization:

public interface ICountryService
{
    Country[] GetCountries();
}
public class CountryService : ICountryService
{
    private readonly IHostingEnvironment _env;
    public CountryService(IHostingEnvironment env)
    {
        _env = env;
    }
    public Country[] GetCountries()
    {
        XmlSerializer ser = new XmlSerializer(typeof(Container));
        FileStream myFileStream = new FileStream(_env.ContentRootPath + "\\Countries\\en-GB.xml", FileMode.Open);
        return ((Container)ser.Deserialize(myFileStream)).Countries;
    }
}

Then register service in ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.AddSingleton<ICountryService, CountryService>();
    }

Finally inject and use it anywhere(such as in a controller)

public class SomeController : Controller
{
    public SomeController(ICountryService countryService)
    {
         // use it
    }
}

Check Also

[Download] Rom Global for Samsung Galaxy Note8 Korea

[Download] Rom Global for Samsung Galaxy Note8 Korea Global rom for Samsung Galaxy Note 8 …

Trả lời

Thư điện tử của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *