我试图计算Team Element中的值,抛出所有Xml节点并以此格式填充到List框:Team1,Count 3。 Thnx寻求帮助
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Team");
foreach (XmlNode xNode in nodeList)
{
foreach (var item in xNode)
{
lstRegPartiData.Items.Add(xNode.InnerText + item);
}
}
这里我尝试按值计算元素。
这是我的xml模板。
<Participants>
<Participant>
<DateTime>21.04.2018</DateTime>
<FullName>N1</FullName>
<Email>email@gmail.com</Email>
<Phone>123456789</Phone>
<DateOfBirth>00/00/1988</DateOfBirth>
<Team>Team1</Team>
<MainWeapon>T1</MainWeapon>
<MainWeaponChrono>120-130 m\s</MainWeaponChrono>
<WeaponClass>C1</WeaponClass>
<Comment>Hello World</Comment>
</Participant>
<Participant>
<DateTime>21.04.2018</DateTime>
<FullName>N1</FullName>
<Email>email@gmail.com</Email>
<Phone>987654321</Phone>
<DateOfBirth>00/00/1988</DateOfBirth>
<Team>Team1</Team>
<MainWeapon>T1</MainWeapon>
<MainWeaponChrono>120-130 m\s</MainWeaponChrono>
<WeaponClass>C1</WeaponClass>
<Comment>My Comment</Comment>
</Participant>
<Participant>
<DateTime>21.04.2018</DateTime>
<FullName>N1</FullName>
<Email>email@gmail.com</Email>
<Phone>123456789</Phone>
<DateOfBirth>00/00/1988</DateOfBirth>
<Team>Team1</Team>
<MainWeapon>T1</MainWeapon>
<MainWeaponChrono>120-130 m\s</MainWeaponChrono>
<WeaponClass>C1</WeaponClass>
<Comment>Hello World</Comment>
</Participant>
</Participants>
答案 0 :(得分:0)
如果我们假设您的xml
类似于:
<Root>
<Team name="team1">
<Participants>
<Participant>
</Participant>
<Participant>
</Participant>
<Participant>
</Participant>
</Participants>
</Team>
<Team name="team2">
<Participants>
<Participant>
</Participant>
<Participant>
</Participant>
</Participants>
</Team>
</Root>
然后将您的代码更改为:
XDocument xdoc = XDocument.Load(@"your xml path");
var teams = xdoc.Descendants("Team");
foreach (XElement team in teams)
{
var firstElement = team.Elements();//Get all elements, here is only one element
var participants = firstElement.Elements();
int teamCount = participants.Count();
var teamName = team.FirstAttribute.Value;
Console.Out.WriteLine("{0} contains {1} member(s)...", teamName, teamCount);
}
Console.ReadLine();
注释:
1-每个xml
文件必须不包含一个根元素,此处为<Root>
。
2-我认为每个team
元素中都有一个元素,因此team.Elements()
会为您提供所有元素。
3-我认为每个名为team
的{{1}}元素都有一个属性,因此name
会为team.FirstAttribute.Value
提供name
元素,否则你应该使用类似team
的内容来获取属性。
答案 1 :(得分:0)
也许你可以做这样的事情
XmlDocument readDoc = new XmlDocument();
readDoc.Load(@"XML.xml");
var Node = readDoc.SelectNodes("Participants/Participant/Team");
Dictionary<string, int> teamList = new Dictionary<string, int>();
foreach (XmlNode n in Node)
{
if (teamList.ContainsKey(n.InnerText))
teamList[n.InnerText]++;
else
teamList.Add(n.InnerText, 1);
}
我知道它看起来不太好但是应该可行