如何用jQuery通过XML中特定元素值查找同级元素值?
用jQuery查找指定标题书籍的作者、年份和价格
针对你提供的XML结构,要找到标题为Harry Potter的书籍对应的作者、出版年份和价格,可以按以下步骤实现:
实现代码
// 加载XML文件(如果XML是本地字符串,直接转为jQuery对象即可) $.get('books.xml', function(xml) { const $xmlDoc = $(xml); // 精确匹配标题为"Harry Potter"的书籍节点 const $targetBook = $xmlDoc.find('title').filter(function() { return $(this).text().trim() === 'Harry Potter'; }).parent('book'); // 提取对应字段的值 const author = $targetBook.find('author').text().trim(); const year = $targetBook.find('year').text().trim(); const price = $targetBook.find('price').text().trim(); // 输出结果(可根据需求替换为DOM渲染等操作) console.log(`作者:${author}`); console.log(`出版年份:${year}`); console.log(`价格:${price}`); });
关键说明
- 用
filter()做精确文本匹配:相比:contains()选择器,这种方式可以避免匹配到包含"Harry Potter"的其他标题(比如"Harry Potter and the Sorcerer's Stone")。 - 通过
parent('book')定位到标题对应的书籍父节点,再从中查找同级的author、year、price元素。 - 如果XML是直接以字符串形式存在的,无需用
$.get,直接转成jQuery对象即可:const $xmlDoc = $(yourXmlString);
内容的提问来源于stack exchange,提问作者Venkatraj GM
相关产品推荐
相关产品推荐

