6

我已经使用 .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>
4

1 回答 1

14

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

[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") 
    };
}
于 2013-04-22T16:00:58.760 回答