我正在使用JavaScript在浏览器中解析XML文档。 XML是这样的:
<product product_id='266629' name='Pink Net Ankle Socks' sku_number='00100003396'>
<category>
<primary>Accessories</primary>
</category>
<description>
<short>Pink Net Ankle SocksThese light and airy fish net style socks are ideal for wearing with ankle style shoe boots. - Ankle length- 84% Nylon, 16% Elastane</short>
</description>
</product>
<product product_id='266630' name='Nude Spot Ankle Socks' sku_number='00100003397'>
<category>
<primary>Accessories</primary>
</category>
<description>
<short>Nude Spot Ankle SocksThese light and airy socks are ideal for wearing with ankle style shoe boots. - Ankle length- 90% Nylon, 10% Elastane</short>
</description>
</product>
因此,我使用getElementsByTagName()
或querySelectorAll()
获取所有<product>
元素,然后遍历生成的数组:
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","35605_3307557_26408825_cmp.xml",false);
xmlhttp.send();
var myXmlDoc = xmlhttp.responseXML;
var products = myXmlDoc.getElementsByTagName('product');
for (var i = 0; i < products.length; i++) {
doSomething(products[i]);
}
问题是products
也包含结束标记!即products[0]
是一个健康的元素,包含我需要的所有信息,products[1]
只是一个没有属性和内在内容的空元素(我假设它是因为它{{1} }),</product>
没关系,等等。
我通过仅使用偶数索引(products[2]
)迭代元素来解决这个问题,但这感觉非常错误。
如何获得没有结束标记的元素数组?