C# reads the data in the XML file sanxai.xml, and finds the average value and the number of data greater than 160. The node name is HZPJ, and the field of the element is Num.

0. Import the system.xml namespace

1. Create the XmlDocument instance object xmlDoc and load it using the Load("path") method

2. Use the DocumentElement attribute under XmlDocment to obtain its root node root, and the return value is of XmlNode type

3. HZPJ nodes are obtained using the SelectNodes ("type field") method under XmlNode, and the return value is of XmlNodeList type.

ps. XmlNodeList is essentially an array whose elements are of type XmlNode, and can be traversed using foreach (XmlNode a in alist){}

4. Each node includes a set of nodes shaped like key-value pairs. SelectSingleNode("Field") under XmlNode obtains the corresponding key-value pair node. At this time, the internal text can be obtained through the InnerText attribute under XmlNode.

ps. You can use the float.Parse() method to convert the obtained text into a floating point type.

// 加载XML文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"E:\Documents\code\sanxai.xml");

// 获取根节点
XmlNode root = xmlDoc.DocumentElement;

// 获取所有HZPJ节点
XmlNodeList hzpjNodes = root.SelectNodes("HZPJ");

// 总数和计数器
float sum = 0;
int count = 0;
int countGreaterThan160 = 0;

// 遍历所有HZPJ节点并计算总和
foreach (XmlNode hzpjNode in hzpjNodes)
{
    // 获取Num节点的值
    XmlNode numNode = hzpjNode.SelectSingleNode("Num");
    float num = float.Parse(numNode.InnerText);

    sum += num;
    count++;

    if (num > 160)
    {
        countGreaterThan160++;
    }
}

// 计算平均值
float average = sum / count;

// 输出结果
Console.WriteLine("平均值:" + average);
Console.WriteLine("大于160的个数:" + countGreaterThan160);

Guess you like

Origin blog.csdn.net/qq_51943845/article/details/132183557