简体   繁体   中英

xml into html using javascript or jquery

i have xml file which contains some details i want to pick some value from them i did that javascript but i it is not close to my requirment, i want pick value from condition wise.

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

this is the a example i have lost of data within xml file.

javascript in header part

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

code in body part

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

please note my code is getting first edata value in first div i want to get the china price value by condition.

I assume that since you tagged "jquery" on this, that you're using jquery (though your code example doesn't imply that). With jQuery you could (get your data much more succinctly using jQuery.ajax and then...) :

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

If you don't want to use jQuery, you'll have to to it with a loop of course:

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

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.

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