用于包含带有SKU和数量的销售订单和明细的XML字符串...

var myOrders =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<Orders>" +
   "<Order>" +
      "<OrderHeader>" +
          "<OrderNo>12345</OrderNo>" +
      "</OrderHeader>" +
      "<OrderDetails>" +
         "<Sku>ABC</Sku>" +
         "<Qty>2</Qty>" +
         "<Sku>DEF</Sku>" +
         "<Qty>3</Qty>" +
      "</OrderDetails>" +
   "</Order>"....
"</Orders>";


我可以像这样用Mozill中的javascript解析。

parser=new DOMParser();
xmlDoc=parser.parseFromString(myOrders,"text/xml");
myValue = xmlDoc.getElementsByTagName("Order");

// list all all SKUs ordered
for(i = 0; i < myValue.length; i++){
    console.log(myValue);
    var order = myValue[i].firstChild.firstChild.firstChild.nodeValue;
    document.write(order + "<br>");
}


我可以替换此行:

    var order = myValue[i].firstChild.firstChild.firstChild.nodeValue;


有一些更具体的

就像是...

  var order = myValue[i]['Order']['OrderDetail']['Sku'].nodeValue;

最佳答案

您可以尝试querySelector

myValue[i].querySelector('OrderHeader > OrderNo').textContent


还考虑querySelectorAll

var elements = xmlDoc.querySelectorAll("Order > OrderHeader > OrderNo");
for(var i = 0; i < elements.length; i++){
    var order = elements[i].textContent;
}

09-27 01:12