如何在MVC核心(1.0.0)中读取xml文档?

Rob*_*urd 2 asp.net-core-mvc asp.net-core asp.net-core-1.0

我是网络编程的新手,决定从.net 4.5切换到.net核心.

我的项目在以下位置有一个静态xml文档:

wwwroot文件/国家/ EN-GB.xml

如何在指定的路径上读取xml文件?最终我将数据转换为SelectList.

在.net 4.5中,我使用DataSet和HttpConext ... MapPath来读取不再适用于核心mvc的xml文档.

任何建议都非常欢迎.

ade*_*lin 5

首先,不要将您的数据源放入wwwroot文件夹,因为它是公开提供的.看看官方文档:

应用程序的Web根目录是项目中用于公共静态资源(如css,js和image文件)的目录.静态文件中间件默认只提供来自Web根目录(和子目录)的文件.

因此Countries,在项目的根文件夹中移动文件夹.

要读取xml数据,您可以使用XmlSerializer.我将尝试演示如何读取xml文件:

首先我假设您有xml内容,如下所示:

<?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>
Run Code Online (Sandbox Code Playgroud)

首先描述类型

public class Country
{
    public string Code { get; set; }
    public string Title { get; set; }
}
public class Container
{
    public Country[] Countries { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

之后,为xml反序列化创建服务:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在ConfigureServices方法中注册服务:

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.AddSingleton<ICountryService, CountryService>();
    }
Run Code Online (Sandbox Code Playgroud)

最后注入并在任何地方使用它(例如在控制器中)

public class SomeController : Controller
{
    public SomeController(ICountryService countryService)
    {
         // use it
    }
}
Run Code Online (Sandbox Code Playgroud)