返回带有XML数据的HttpResponseMessage

本文关键字:HttpResponseMessage 数据 XML 返回 | 更新日期: 2023-09-27 18:10:16

我使用。net创建了一个WebAPI。API从xml文件中读取/写入数据。我有下面的代码,它返回没有根元素的匹配元素。我怎么让它带根返回?

API控制器:

 [HttpGet]
 public HttpResponseMessage GetPerson(int personId)
 {
    var doc = XDocument.Load(path);
    var result = doc.Element("Persons")
           .Elements("Person")
           .Single(x => (int)x.Element("PersonID") == personId);
    return new HttpResponseMessage() { Content = new StringContent(string.Concat(result), Encoding.UTF8, "application/xml") };
 }
结果:

<Person>
  <PersonID>1</PersonID>
  <UserName>b</UserName>
  <Thumbnail />
</Person><Person>
  <PersonID>2</PersonID>
  <UserName>b</UserName>
  <Thumbnail />
</Person><Person>
  <PersonID>4</PersonID>
  <UserName>a</UserName>
  <Thumbnail>a</Thumbnail>
</Person>

返回带有XML数据的HttpResponseMessage

您可以将结果封装在根元素中:

[HttpGet]
public HttpResponseMessage GetPerson(int personId)
{
    var doc = XDocument.Load(path);
    var result = doc
        .Element("Persons")
        .Elements("Person")
        .Single(x => (int)x.Element("PersonID") == personId);
    var xml = new XElement("TheRootNode", result).ToString();
    return new HttpResponseMessage 
    { 
        Content = new StringContent(xml, Encoding.UTF8, "application/xml") 
    };
}
相关文章:
  • 没有找到相关文章