我的 xml 看起来像这样:
<marker>
<name>Ada County Jail</name>
<adr>Boise</adr>
<state>Idaho</state>
<geo>43.6073458, -116.2698884</geo>
<tag>County</tag>
<ice>t</ice>
<url title="Ada County Jail">https://adacounty.id.gov/sheriff/ada-county-jail/</url>
<url title="Inmates">https://apps.adacounty.id.gov/sheriff/reports/inmates.aspx</url>
</marker>
我正在使用jquery。我在这里提取 URL 元素:
function parseXml(xml)
{
$(xml).find("marker").each(function()
{
var url = $(this).find('url').map(function(i,v){return ($(v).text());}).get();
...
我正在尝试提取 url 元素的 title 属性的文本,以便 HTML 链接如下所示:
Link: Ada County Jail
Link: Inmates
此代码失败,并显示无法识别的表达式消息:
for (i=0;i<url.length;i++){
var web = url[i];
var y = $(xml).find(url[1]).attr("title");
html += '<a href="' + web + '">Link: ' + y + '</a>';
}
这是我第一次尝试访问属性。帮助。
要从
title
元素中提取 url
属性,您可以像这样修改代码:
$xml.find("marker").each(function() {
$(this).find('url').each(function() {
const url = $(this).text();
const title = $(this).attr('title');
$('#links').append(`<a href="${url}">Link: ${title}</a><br>`);
});
});
这是一个可以在您的计算机上运行的工作示例:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>XML Parsing Test</title>
</head>
<body>
<div id="links"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const xmlString = `
<marker>
<name>Ada County Jail</name>
<adr>Boise</adr>
<state>Idaho</state>
<geo>43.6073458, -116.2698884</geo>
<tag>County</tag>
<ice>t</ice>
<url title="Ada County Jail">https://adacounty.id.gov/sheriff/ada-county-jail/</url>
<url title="Inmates">https://apps.adacounty.id.gov/sheriff/reports/inmates.aspx</url>
</marker>
`;
const xml = $.parseXML(xmlString);
const $xml = $(xml);
$xml.find("marker").each(function() {
$(this).find('url').each(function() {
const url = $(this).text();
const title = $(this).attr('title');
$('#links').append(`<a href="${url}">Link: ${title}</a><br>`);
});
});
</script>
</body>
</html>
如果这不能解决您的问题,请在评论中告诉我,我会修改我的答案。