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

99封情书 提交于 2019-12-01 11:09:44

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!