这里介绍两种JavaScript解析XML字符串的函数:
- 使用DOMParser
步骤:
- 创建一个XML字符串变量
- 建立一个DOMParser对象
- 将XML字符串传递给DOMParser对象的parseFromString方法
- 执行XPath选择器
示例代码:
const xmlString =
`<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const titles = xmlDoc.evaluate("//title", xmlDoc, null, XPathResult.ANY_TYPE, null);
let title = titles.iterateNext();
while (title) {
console.log(title.textContent);
title = titles.iterateNext();
}
输出:
Everyday Italian
Harry Potter
Learning XML
- 使用$.parseXML
步骤:
- 按照jQuery库文件
- 调用$.parseXML方法将XML字符串转换为XML Document对象。
- 借助jQuery的封装方法,如$()、find()、text()进行常规的操作
示例代码:
const xmlString =
`<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>`;
const xmlDoc = $.parseXML(xmlString);
const $xml = $(xmlDoc);
$xml.find("title").each(function () {
console.log($(this).text());
});
输出:
Everyday Italian
Harry Potter
Learning XML
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:javascript解析xml字符串的函数 - Python技术站