我成功地使用此代码从 App_Data 文件夹加载 XML。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using Newtonsoft.Json;
using System.Xml.Linq;
using System.Xml;
using XMLTest2.Models;
namespace XMLTest2.Controllers
{
public class PeopleController : ApiController
{
public List<XMLpeople> GetAllPeople()
{
var path = HttpContext.Current.Server.MapPath(@"~/App_Data/XML_Test.xml");
List<XMLpeople> people = new List<XMLpeople>();
XMLpeople NewPerson = new XMLpeople();
XDocument doc = XDocument.Load(path);
foreach (XElement element in doc.Descendants("people").Descendants("person"))
{
NewPerson.id = element.Element("id").Value;
NewPerson.name = element.Element("name").Value;
NewPerson.age = element.Element("age").Value;
NewPerson.description = element.Element("description").Value;
people.Add(NewPerson);
}
return people;
}
}
}
现在我希望创建一个从这里到客户端的 Restful 服务。我试图用这些代码解析这个几天。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Xml.Linq;
using System.Xml;
namespace XMLTest2.Models
{
public class PeopleRestService
{
public List<XMLpeople> GetAllPeople()
{
string current_hostname = System.Web.HttpContext.Current.Request.Url.ToString();
string api_url = "api/people";
string url = current_hostname + api_url;
WebClient proxy = new WebClient();
using (var stream = proxy.OpenRead(url))
{
var response = proxy.DownloadString(url);
XmlReader reader = XmlReader.Create(response); //I Got an error here. It says. Illegal characters in path.
DataTable datatable = new DataTable();
datatable.ReadXml(reader);
List<XMLpeople> xxx = new List<XMLpeople>();
xxx = (from DataRow row in datatable.Rows
select new XMLpeople
{
id = row["id"].ToString(),
name = row["name"].ToString(),
age = row["age"].ToString(),
description = row["description"].ToString()
}).ToList();
return xxx;
}
}
}
}
任何帮助或链接都会非常感谢!,并且我是 Asp.net MVC web api 的新手。