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