期中作业求助:统计XML文档中country与contacttitle字段的出现频次
你只需要在原有代码基础上增加计数逻辑即可,具体调整如下:
第一步:页面新增计数结果容器
先在HTML里新增两个容器用来放统计结果:
<!-- 原有表格容器 --> <div id="table"></div> <!-- 新增计数容器 --> <h3>国家统计结果</h3> <div id="countryCount"></div> <h3>联系人职位统计结果</h3> <div id="titleCount"></div>
第二步:调整JS逻辑增加计数功能
修改后的imAnnoyed函数如下,核心是新增两个计数对象,遍历节点时累加计数,遍历完成后生成统计HTML插入页面,同时修复了原有代码表格行闭合标签写错的问题:
function imAnnoyed(xml) { var i; xmlDoc = xml.responseXML; const mad = xmlDoc.getElementsByTagName("forMid"); // 初始化两个计数对象 const countryCounter = {}; const titleCounter = {}; var table = "<col><col><col><col><col><tr><th>Business ID</th><th>Customer Name</th><th>Title</th><th>City</th><th>Country</th></tr>"; for (i = 0; i < mad.length; i++) { // 提取字段值 const cust = mad[i].getElementsByTagName("cust")[0].childNodes[0].nodeValue; const name = mad[i].getElementsByTagName("abc")[0].childNodes[0].nodeValue; const contactTitle = mad[i].getElementsByTagName("contacttitle")[0].childNodes[0].nodeValue; const city = mad[i].getElementsByTagName("city")[0].childNodes[0].nodeValue; const country = mad[i].getElementsByTagName("country")[0].childNodes[0].nodeValue; // 累加计数:不存在就设为1,存在就+1 countryCounter[country] = countryCounter[country] ? countryCounter[country] + 1 : 1; titleCounter[contactTitle] = titleCounter[contactTitle] ? titleCounter[contactTitle] + 1 : 1; // 拼接表格行 table += "<tr><td>" + cust + "</td><td>" + name + "</td><td>" + contactTitle + "</td><td>" + city + "</td><td>" + country + "</td></tr>"; } // 渲染表格 document.getElementById("table").innerHTML = table; // 生成国家统计HTML let countryHtml = ''; for (let country in countryCounter) { countryHtml += "<p>" + country + ": " + countryCounter[country] + " Count</p>"; } document.getElementById("countryCount").innerHTML = countryHtml; // 生成职位统计HTML let titleHtml = ''; for (let title in titleCounter) { titleHtml += "<p>" + title + ": " + titleCounter[title] + " Count</p>"; } document.getElementById("titleCount").innerHTML = titleHtml; }
效果说明
针对你提供的XML片段,最终统计结果为:
- Germany: 1 Count
- Mexico: 2 Count
- Sales Representative: 1 Count
- Owner: 2 Count
完全符合要求的输出格式,所有语法兼容低版本浏览器无需额外适配。
内容的提问来源于stack exchange,提问作者wavedbabe
相关产品推荐
相关产品推荐

