Domanda

this is my first question here and I am quite new to web development world. I have a simple question so I don't want to annoy you with all my code, I'll make you a simpler example:

I have an XML that looks like this, lets call it "example.xml":

<a>
   <b>1</b>
   <a>
      <b>2</b>
      <c>3</c>
   </a>
</a>

So there are multi-levels of 'a' containing or not a 'c' element. When I am parsing this xml using

$.ajax({type: "GET",async: false, cache: false, url: "example.xml",dataType: "xml",success: parseXml,  error: function(xhr, status, error) {alert(error)}});

parseXml would go like this :

function parseXml(xml){
    var result = new Object()
    $(xml).find('a').each(function(){
       result.b = $(this).find('b:first').text()
       result.c = $(this).find('c:first').text()
    }
}

So my problem here is that this JQuery will find a 'c' into the first level 'a' even if there is not. I think it searches within the second 'a' to find a 'c'. That's why I needed to add ":first:" into the find() function so that it wouldn't return me the second 'b'... I think it is not the best way to go, since if the 'b' was declared after the second level 'a', I would have got the second level 'b' instead... I don't know if you are following but here would be my question:

  1. Is that a proposer XML file?
  2. If it is not, assuming I can't change it, how can I get a propoper XML parser that wouldn't get its information from the second level?

Thanks you so much for your help!

È stato utile?

Soluzione

Try can use .children to search only in direct children

function parseXml(xml){
    var result = new Object()
    $(xml).find('a').each(function(){
       result.b = $(this).children('b').text()
       result.c = $(this).children('c').text()
    }
}

.find() will search descendants in all levels

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top