繁体   English   中英

使用javascript或jquery将xml转换为html

[英]xml into html using javascript or jquery

我有xml文件,其中包含一些详细信息,我想从中选择一些值,我做了那个javascript,但是我离我的要求不近,我想从条件方面选择值。

<edata updated="2012:12:32.697" product_type_id="3" product_type="epack" headline="Gold Coast" destination="india" localised_destination="Gold Coast" headline_no_html="Gold Coast" price="372" />
<edata updated="2012:12:32.697" product_type_id="3" product_type="epack" headline="Gold Coast" destination="china" localised_destination="Gold Coast" headline_no_html="Gold Coast" price="450" />

这是我在xml文件中丢失数据的示例。

标头中的javascript

<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","edata.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
</script>

身体部位的代码

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
    var x=xmlDoc.getElementsByTagName("edata");
    document.write("<div>");
    document.write(x[0].getAttribute('price'));
    document.write("</div>");
  </script>
</div>

请注意,我的代码在第一个div中获取第一个edata值,我想按条件获取中国价格值。

我假设由于您在此上标记了“ jquery”,所以您正在使用jquery(尽管您的代码示例并不暗示这一点)。 使用jQuery,您可以(使用jQuery.ajax然后再更简洁地获取数据):

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
   $xml = $( xmlDoc ),
   $title = $xml
     .find( "edata[price]" ) //gets all nodes with a price
     .filter( function(i) {
         // filter out all the items that have a price less than 100
         return ( parseInt( this.attr("price") ) > 100 ) ? true : false;
     })
   ; 
  </script>
</div>

如果您不想使用jQuery,则必须循环使用它:

<div id="Frame2">
  <script type="text/javascript">
    function load()
    {
      alert("Page is loaded");
    }
    var x=xmlDoc.getElementsByTagName("edata");
    var i, l = x.length;
    var price;
    for( i = 0; i < l; i++ ){
      price = x[i].getAttribute( 'price' );
      if( typeof price !== "undefined" && parseInt( price ) > 100 ){
        document.write("<div>" + price + "</div>");
      }
    }
  </script>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM