1

I am able to read my local .xml file with this code. My question is, is it possible to get certain xml element if all my elements have unique id (as child nodes) without looping the whole xml file? for example, get name and year of item with id=3.

     $.ajax({

                    type: "GET",
                    url: "Cars.xml",
                    dataType: "xml",
                    success: getDataFromXml

                });
     function getDataFromXml(xml){

           $(xml).find("Car").each(function(){
           ....
     }

XML

<Cars>
<Car>
    <Id>1</Id>
    <Name>Tornado</Name>
    <Model>Ferrari</Model>
    <Year>1943</Year>
</Car>
    <Car>
    <Id>2</Id>
    <Name>Tiger</Name>
    <Model>Ferrari</Model>
    <Year>1943</Year>
</Car>
    <Car>
    <Id>3</Id>
    <Name>Cat</Name>
    <Model>Ferrari</Model>
    <Year>1943</Year>
</Car>
</Cars>
Procode
  • 65
  • 11

1 Answers1

1
var xmlDoc = $.parseXML(xml),
$xml = $( xmlDoc ),
$cars = $xml.find( "Car" );

This will do it. For more information, look here

You can use find and has to get the element. First you find the element car, then you check if the element has the id, that contains 3 as value. This will give you $.find( "Car" ).has( "Id:contains('3')" ). I made an example for you, that will return the Car Element with Id=3. Now you do not need to iterate over all "Car-Elements".

var xml = "<Cars><Car><Id>1</Id><Name>Tornado</Name><Model>Ferrari</Model><Year>1943</Year></Car><Car><Id>2</Id><Name>Tiger</Name><Model>Ferrari</Model><Year>1943</Year></Car><Car><Id>3</Id><Name>Cat</Name><Model>Ferrari</Model><Year>1943</Year></Car></Cars>";

var xmlDoc = $.parseXML(xml);
var $xml = $( xmlDoc );
var $cars = $xml.find( "Car" ).has( "Id:contains('3')" );

console.log($cars[0].innerHTML)
.as-console-wrapper {
  min-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
DomeTune
  • 1,401
  • 10
  • 21
  • How to acces element with id 3 only? – Procode Feb 28 '17 at 22:46
  • I dont know you xml, so i dont know how to select it. Maybe add a snippet to your question, and tell me if you updated it. – DomeTune Mar 01 '17 at 07:24
  • Here you go, how could i accec all the elements of the car with the id=3 without looping the whole xml? – Procode Mar 01 '17 at 10:34
  • 1
    I updated my answer. Check it out. Is this what you need? – DomeTune Mar 01 '17 at 11:31
  • Yes indeed, thanks alot :) Now im able to find specific car element. How can I get the name property of the same element and also properties one level deep in the same element. What is the meaning of cars[0]? if i change the number, I se no changes. – Procode Mar 02 '17 at 10:06
  • @Procode the `$cars` is an array, which has the `car elements`. With `$cars[0]` i get the first an only element, that is the `car element` with the `id = 3`. I dont know enought about jquery to tell you that. maybe ask a new question, with this specific content. – DomeTune Mar 02 '17 at 19:15