我正在尝试从 xml 列表中获取项目并打印为 html 页面。 有一个小问题。您可以在这里看到问题:http://daisy.unlu.co/handshake_api/ .
应该有2行我不知道为什么有6行。我打印 sku、描述、价格和图像 url。正如您所看到的,变体具有相同的图像网址、不同的价格、不同的描述和不同的 sku。
<?xml version='1.0' encoding='utf-8'?>
<response>
<objects type="list">
<object type="hash">
<imageURL>
http://5387f51cd2471f8fea9a-807406182e5fe44c6ce394326aa32939.r89.cf2.rackcdn.com/image/189589cd5409c29b9efa1281d66b41bba0c101d6.jpg
</imageURL>
<variants type="list">
<object type="hash">
<sku>IRIS3-1</sku>
<dimensions type="list">
<object type="hash">
<dimension>Dimension</dimension>
<value>Irish Spring Bar Soap-1 (3 x 3.75 Oz) x 18</value>
</object>
</dimensions>
<unitPrice>31.00</unitPrice>
</object>
<object type="hash">
<sku>IRIS3-2</sku>
<dimensions type="list">
<object type="hash">
<dimension>Dimension</dimension>
<value>Irish Spring Bar Soap-2 (3 x 3.75 Oz) x 18</value>
</object>
</dimensions>
<unitPrice>32.00</unitPrice>
</object>
</variants>
</object>
</objects>
</response>
XML 列表
$(document).ready(function(){
$.get("items2.xml",{},function(xml){
// Build an HTML string
myHTMLOutput = '';
myHTMLOutput += '<table width="100%" border="1" cellpadding="0" cellspacing="0">';
myHTMLOutput += '<th>SKU</th><th>Description</th><th>Price</th><th>Image</th>';
var mydata = " ";
var imageURL = " ";
var sku = " ";
var name = " ";
var unitPrice = " ";
$('objects object',xml).each(function(i) {
imageURL = $(this).find("imageURL").text();
//var sku;
//var name;
//var unitPrice;
$(this).find('variants object').each(function(){
sku = $(this).find("sku").text();
name = $(this).find('dimensions object value').text();
unitPrice = $(this).find("unitPrice").text();
//console.log(unitPrice);
mydata = BuildStudentHTML(sku,name, unitPrice,imageURL);
myHTMLOutput = myHTMLOutput + mydata;
});
// Build row HTML data and store in string
});
myHTMLOutput += '</table>';
// Update the DIV called Content Area with the HTML string
$("#ContentArea").append(myHTMLOutput);
});
});
function BuildStudentHTML(sku, name, unitPrice, imageURL){
output = '';
output += '<tr>';
output += '<td>'+ sku + '</td>';
output += '<td>'+ name +'</td>';
output += '<td>'+ unitPrice +'</td>';
output += '<td>'+ imageURL +'</td>';
output += '</tr>';
return output;
}
最佳答案
尝试使用直接子选择器>
:$('objects > object')
当循环同名嵌套节点时。这将选择 object
objects
的直接子节点.
$('objects object')
将选择object
objects
的子节点AND variants
的嵌套子级节点。它基本上是“给我 object
嵌套或其他方式下的所有 objects
节点。”
如果没有有效的 jsFiddle 示例,调试这个有点困难,所以如果它不起作用,请不要对我投反对票。
关于jQuery 获取嵌套 XML 列表并发布为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34297453/