我在尝试从具有2个不同后代的xml文件中提取数据时遇到了一些问题。
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Male>
<Person id="1" Name="Joe" Age="35" />
...... Some more data
<Person id="6" Name="Hank" Age="55" />
</Male>
<Female>
<Person id="4" Name="Jane" Age="28" />
...... Some more data
<Person id="9" Name="Jude" Age="32" />
</Female>
所以我想只提取后代女性,所以这是我的代码。
private int personId;
private string personName;
private int personAge
private async void GetPersonDetails()
{
try
{
string personDetail = "http://localhost/people/directory.xml";
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, personDetail
// Send the request to the server
HttpResponseMessage response2 = await httpClient.SendAsync(requestMessage);
// Just as an example I'm turning the response into a string here
string responseAsString = await response2.Content.ReadAsStringAsync();
System.Xml.Linq.XDocument _xdoc = System.Xml.Linq.XDocument.Parse(responseAsString);
var peopleData = from person in _xdoc.Descendants("Female")
select new
{
id = person.Attribute("id").Value,
name = person.Attribute("Name").Value,
age = person.Attribute("Age").Value
};
int peopleIdx = 0;
foreach (var pDetails in peopleData)
{
personId = pDetails.id;
personName = pDetails.name;
personAge = pDetails.age;
peopleIdx++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
它还会提取男性细节。我怎样才能从女性后代那里获得所有数据?基本上,用户可以搜索男性或女性以获得结果。
答案 0 :(得分:1)
您需要选择名为Person
的元素,这些元素是Female
的子元素。您可以使用Enumerable.SelectMany()
获取Female
元素的子元素,然后处理其数据:
var people = _xdoc.Descendants("Female")
.SelectMany(e => e.Descendants("Person"))
.Select(e => new
{
Id = e.Attribute("id").Value,
Name = e.Attribute("Name").Value,
Age = e.Attribute("Age").Value
});