如何从XML文件中提取指定月份的所有日期数据?
问题描述
已实现从URL拉取XML数据,并能通过split('/')拆分dd/mm/yyyy格式的日期,现在需要提取月份值为1的所有日期数据,期望控制台输出匹配的日期字符串。
原代码
console.log("Fetching from URL: ", currenturl); fetch(currenturl) .then(response => response.text()) .then(data => { const parser = new DOMParser(); const xml = parser.parseFromString(data, "application/xml"); var getdate = xml.getElementsByTagName("date"); var amountOfdate = getdate.length; //display the total amount of date element in the xml file. console.log(amountOfdate); for (let i = 0; i < amountOfdate; ++i){ var getstringdate = getdate[i].childNodes[0].nodeValue; var arrmonth = getstringdate.split("/"); var getmonth = parseInt(arrmonth[1]); } console.log("stop"); }) .catch(console.error);
XML示例
<datedata> <month> <date>01/01/2007</date> </month> <month> <date>01/01/2007</date> </month> <month> <date>01/02/2007</date> </month> </datedata>
解决方案
在循环中添加月份匹配判断,当提取的月份等于目标值时输出对应日期即可,修改后的代码如下:
console.log("Fetching from URL: ", currenturl); fetch(currenturl) .then(response => response.text()) .then(data => { const parser = new DOMParser(); const xml = parser.parseFromString(data, "application/xml"); const getdate = xml.getElementsByTagName("date"); const targetMonth = 1; // 指定要提取的目标月份 console.log("Total date elements: ", getdate.length); for (let i = 0; i < getdate.length; ++i){ const dateStr = getdate[i].childNodes[0].nodeValue.trim(); // 去除XML中可能存在的空格 const dateParts = dateStr.split("/"); const month = parseInt(dateParts[1], 10); // 按十进制解析月份,避免进制歧义 // 匹配目标月份则输出日期 if (month === targetMonth) { console.log(dateStr); } } console.log("stop"); }) .catch(console.error);
关键优化点
- 新增
targetMonth变量,方便后续快速修改目标月份 - 调用
trim()处理日期字符串,避免XML中的空格干扰拆分结果 - 给
parseInt添加第二个参数10,确保按十进制解析数值 - 添加
if判断逻辑,精准筛选出目标月份的日期
运行修改后的代码,控制台将输出:
01/01/2007 01/01/2007
内容的提问来源于stack exchange,提问作者Chronicle
相关产品推荐
相关产品推荐

