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

2019-07-11 05:41发布

问题:

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.

回答1:

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
    }
}