Javascript从id获取信息

时间:2016-03-16 22:34:15

标签: javascript jquery xml

我有这个XML:

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product top-level-category="cat" sub-level-category="cat-sub">
    <id>235</id>
    <title>title</title>
    <brand>brand 1</brand>
    <price>200.00</price>
    <description>This is my amazing description</description>
    <spec>
        <s1>24.2</s1>
        <s2>23.5 x 15.6 CMOS</s2>
        <s3>Auto, 100-12800</s3>
        <s4>Nikon F Mount</s4>
    </spec>
</product>
<products>

如何通过获得产品的ID来获得标题,品牌,价格,s1,s2,s3,s4等?

我目前失败的尝试:

$(productsDomTree).each(function() {
                    var name = $(this).find('id').text();

                    if (name = vars['id']) {
                        alert(name);
                    }
                });

所有这一切都告诉我它找到了正确的元素

更新了有效的代码,但始终选择第二个代码:

var id = vars['id'];
                alert(id);
                var ids = ($products).find('id');
                var id = ids.filter(function(id) { return !!$(this).text() == id; });
                var product = id.parent();
                var title = product.find( "title" ).text();
                alert(title);

2 个答案:

答案 0 :(得分:0)

如果您将xml字符串提供给jQuery的parseXML函数,则可以执行此操作:

var id = 235;
var xml = "Your XML Here!";
var xmlDoc = $.parseXML( xml );
var $xml = $( xmlDoc );
var ids = $xml.find('id');
var id = ids.filter(function(id) { return !!$(this).text() == id; });
var product = id.parent();
var title = product.find( "title" ).text();

答案 1 :(得分:0)

CSS选择器无法访问元素的文本内容。然后,我推荐XPath,例如

var xmlString = '<?xml version="1.0" encoding="UTF-8"?><products><product top-level-category="cat" sub-level-category="cat-sub"><id>235</id><title>title</title><brand>brand 1</brand><price>200.00</price><description>This is my amazing description</description><spec><s1>24.2</s1><s2>23.5 x 15.6 CMOS</s2><s3>Auto, 100-12800</s3><s4>Nikon F Mount</s4></spec></product></products>';
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
var iterator = doc.evaluate('//product[id = "235"]/*', doc, null, XPathResult.ANY_TYPE, null);
var obj = {}, val;
while (val = iterator.iterateNext())
  obj[val.nodeName] = val.textContent;
document.write('<pre>' + JSON.stringify(obj, null, 2) + '</pre>');