Extracting text from an XML file based on an eleme

2019-08-28 06:31发布

I have a simple XML file that looks like this:

<?xml version="1.0" ?>
<devices>

<device>
<name>Inside</name>
<value>67.662498</value>
</device>

<device>
<name>Outside</name>
<value>69.124992</value>
</device>

</devices>

I want to extract the temperature (value) for "Outside" using JavaScript. Here is what I have so far:

<script type="text/javascript">
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","data.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("value").innerHTML=
xmlDoc.getElementsByTagName("value")[0].childNodes[0].nodeValue;
</script>

When I run this inside an HTML file, it pulls the name "Inside" and its temperature value and not the Outside temperature value. I just want to be able to run this and have "69.124992" show up as the value. What do I need to add to parse this file so it looks only for the device with the name "Outside"?

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-28 06:47

Your current implementation is just getting the first occurrence of name and value and displaying the value, Instead why not just loop

var names = xml.getElementsByTagName('name');
for (var iDx = 0; iDx < names.length; iDx++) {
     if (names[iDx].childNodes[0].nodeValue == 'Outside') {
         jQuery('#name').text(names[iDx].childNodes[0].nodeValue);
         jQuery('#value').text(xml.getElementsByTagName('value')[iDx].childNodes[0].nodeValue);
         break;
    }
}

JSFiddle

查看更多
登录 后发表回答