使用XML数据返回HttpResponseMessage

时间:2013-04-22 15:44:46

标签: c# xml asp.net-mvc linq

我使用.NET创建了一个WebAPI。 API从xml文件读取/写入数据。我有以下代码,它返回没有根元素的匹配元素。如何让它以root身份返回?

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>

1 个答案:

答案 0 :(得分:13)

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

[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") 
    };
}