gpt4 book ai didi

javascript - 在 xml 中搜索属性

转载 作者:行者123 更新时间:2023-11-30 00:10:13 25 4
gpt4 key购买 nike

我尝试了很多不同的方法,但运气不好。我要做的就是识别当前 URL 的域并根据域从 XML 文件中提取一个值。

如有任何帮助,我们将不胜感激。

商户.xml

<?xml version="1.0" encoding="utf-8"?>
<catalog>
<merchant id="1">
<domain>http://www.amazon.com</domain>
<affiliate>1</affiliate>
</merchant>
</catalog>

弹出窗口

function ReadXML() {
try {
var xmlPath = "merchants.xml";
$.ajax({
type: "GET",
url: xmlPath,
dataType: "xml",
success: parseXML
});
} catch (e) {
alert("Error while reading XML; Description – " + e.description);
}
}

function parseXML(xml) {
var $merchant = $(xml).find('domain').filter(function() {
return $(this).text() == "http://www.amazon.com";
}).closest('domain');
var affiliate = $('affiliate', $domain).text();

if(window.location.hostname.indexOf("http://www.amazon.com") > -1) {
document.getElementById("demo").innerHTML = affiliate;
}
}
readXML()

弹出窗口

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 75%;
}
#status {
/* avoid an excessively wide status text */
white-space: normal;
text-align: center;
width: 200px;
height: 225px;
overflow: hidden;
max-width: 400px;
word-wrap: normal;
}
</style>
<script type="text/javascript" src="popup.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<table id="demo"></table>
<div id="status"></div>
</body>
</html>

最佳答案

您可以使用 jQuery XML to JSON Plugin 将 XML 转换为 JSON .结果,您将获得一个具有所有属性的 Javascript 对象:

{"merchant":{"domain":"http://www.amazon.com","affiliate":"1","id":"1"}}

完整示例:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="https://jquery-xml2json-plugin.googlecode.com/svn/trunk/jquery.xml2json.js"></script>
<script type="text/javascript">
$(function() {

var
xml,
json;

xml =

'<?xml version="1.0" encoding="utf-8"?>' +
'<catalog>' +
'<merchant id="1">' +
'<domain>http://www.amazon.com</domain>' +
'<affiliate>1</affiliate>' +
'</merchant>' +
'</catalog>';

json = $.xml2json(xml);

alert(json.merchant.domain);
});
</script>

关于javascript - 在 xml 中搜索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36819547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com