So I got this code which gets me the elements from an XML(a product catalog) and lists them in a table. What I want to do now is to return from that XML only 1 product with all it's elements. For example, I want to get from the catalog only the product I want to see that has a certain SERIAL.
This is my XML document:
<CATALOG>
<PRODUCT>
<SERIAL>123ABC</SERIAL>
<PRODNR>1234</PRODNR>
<PRODNM>COOLER</PRODNM>
<ACCNAME>JOHN</ACCNAME>
<NRDOC>0001</NRDOC>
</PRODUCT>
<PRODUCT>
<SERIAL>234BCD</SERIAL>
<PRODNR>2345</PRODNR>
<PRODNM>MOUSEPAD</PRODNM>
<ACCNAME>STEVE</ACCNAME>
<NRDOC>0002</NRDOC>
</PRODUCT>
<PRODUCT>
<SERIAL>345CDE</SERIAL>
<PRODNR>3456</PRODNR>
<PRODNM>KEYBOARD</PRODNM>
<ACCNAME>WILLIAM</ACCNAME>
<NRDOC>0003</NRDOC>
</PRODUCT>
<PRODUCT>
<SERIAL>456DEF</SERIAL>
<PRODNR>4567</PRODNR>
<PRODNM>MOUSE</PRODNM>
<ACCNAME>MARCUS</ACCNAME>
<NRDOC>0004</NRDOC>
</PRODUCT>
</CATALOG>
And this is the code I have so far:
function loadXMLDoc(url) {
var serialNumber = document.getElementById('searchBox').value;
var xmlhttp;
var txt, xx, x, i;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = "<table border='1'><tr><th>Product number</th><th>Product name</th><th>Account name</th><th>Document number</th></tr>";
x = xmlhttp.responseXML.documentElement.getElementsByTagName("PRODUCT");
for (i = 0; i < x.length; i++) {
txt = txt + "<tr>";
xx = x[i].getElementsByTagName("PRODNM");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("PRODNR");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("ACCNAME");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("NRDOC");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
txt = txt + "</tr>";
}
txt = txt + "</table>";
document.getElementById('showTable').innerHTML = txt;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I would use XPath to select necessary PRODUCT node:
var path = '//SERIAL[text()="' + serialNumber + '"]/..';
var x = document.evaluate(path, xmlhttp.responseXML.documentElement, null, 9, null).singleNodeValue;
Note: ( document.selectNodes(xpath)
for IE)
Demo: http://plnkr.co/edit/9hp6kM5OT8LEYrTCrCqN?p=preview
Or you can simple loop through all PRODUCT nodes and filter the one with search ID.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.