XML / javascript解析节点 - 按名称指定子节点

时间:2015-01-17 20:22:38

标签: javascript xml parsing nodes

包含销售订单的XML字符串和包含SKU和Qty的详细信息......

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;

2 个答案:

答案 0 :(得分:1)

您可以尝试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;
}

答案 1 :(得分:0)

使用querySelector和querySelectorAll,这似乎有效。我可以更有效率吗?我似乎不必使用完整路径(A> B&gt; C)。请注意,我在下面的示例中添加了OrderDetail标记。我没有这个验证,但看起来更干净。

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

document.write("</br>4. Get all Orders Numbers and SKU Ordered for each Order</br>");
myOrders= xmlDoc.getElementsByTagName("Order"); 
// iterate through orders
for(x = 0; x < myOrders.length; x++){           
    var myOrder = myOrders[x].querySelector('OrderNo').textContent;
    document.write(myOrder + "</br>");

// iterate through SKUS in each order
    var mySkus = myOrders[x].querySelectorAll('OrderDetail > Sku');     
    for(y = 0; y < mySkus.length; y++){                     
        document.write("-- SKU: " + mySkus[y].firstChild.nodeValue + "</br>");
    }
}
document.write("<hr>");