根据元素的值从XML文件中提取文本? [英] Extracting text from an XML file based on an element's value?

查看:384
本文介绍了根据元素的值从XML文件中提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的XML文件,如下所示:

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>

我想使用JavaScript提取外部"的温度(值).这是我到目前为止的内容:

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>

当我在HTML文件中运行此文件时,它会拉出名称"Inside"及其温度值,而不是外部温度"值.我只希望能够运行它并让"69.124992"显示为该值.我需要添加什么来解析此文件,使其仅查找名称为"Outside"的设备?

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"?

推荐答案

您当前的实现只是获取名称和值的第一个出现并显示该值,而不是为什么不循环

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

这篇关于根据元素的值从XML文件中提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆