xml节点循环取值问题
页面Grid内获取的批量记录已经在后台转换为了xml,其格式为:<records><record><NAME>name1</NAME><MONEY>100</MONEY></record><record><NAME>name2</NAME><MONEY>200</MONEY></record><record>...</record></records>
现在的需求是1、要取出其中所有name节点的值组成"name1/name2"格式;2、所有MONEY节点求和,代码怎么写?非常感谢
------解决方案-------------------- XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"路径");
XmlNodeList names = xmlDoc.SelectNodes(@"//NAME");
StringBuilder sb = new StringBuilder();
foreach (XmlNode name in names)
{
sb.Append(name.InnerText);
sb.Append("/");
}
string r = sb.ToString().TrimEnd('/');
Response.Write(r + "<br/>");
XmlNodeList money = xmlDoc.SelectNodes(@"//MONEY");
int sum = 0;
foreach (XmlNode m in money)
sum += int.Parse(m.InnerText);
Response.Write(sum);
大体上是这样。
------解决方案--------------------
用 linq2xml
C# code
var xdoc = XDocument.Parse("<records><record><NAME>name1</NAME><MONEY>100</MONEY></record><record><NAME>name2</NAME><MONEY>200</MONEY></record><record></record></records>");
var names = string.Join("/", xdoc.Descendants("NAME").Select(node => node.Value).ToArray());
var total = 0;
xdoc.Descendants("MONEY").ToList().ForEach(node => total += Convert.ToInt32(node.Value));
Console.WriteLine(names);
Console.WriteLine(total);
------解决方案--------------------
var xdoc = XDocument.Parse(xml.OuterXml);