tags:

views:

340

answers:

2

I've been using jQuery .find() to do xml traversal, and I'm finding that occasionally I have a child tag in a tree that will collide with a tag somewhere further up the tree. For instance...

<?xml version="1.0" encoding='UTF-8'?>
<userInfo>
   <firstname>This is a firstname</firstname>
   <lastname>This is a last name</lastname>
   <appSpecific>
      <location></location>
      <nickname>First L</nickname>
      <status></status>
      <color>FFB141</color>
      <lastName>Oops, second name</lastName>
      <firstName>Oops, second name</firstName>
      <gender></gender>
      <timezone></timezone>
      <active>true</active>
      <languages></languages>
      <homepage></homepage>      
   </appSpecific>
</userInfo>

Now, when I do this:

var firstname = $(xml).find("firstname").text();    
var lastname = $(xml).find("lastname").text();

The output is the contents of both sets of tags.

Is there a good way to filter out child tags (especially since I know the parent tag I want to filter)?

I was trying some combo of .filter and .children, but can't seem to get it to work. Any help much appreciated.

Thanks, Josh

+1  A: 

You could try using the :first selector:

var firstname = $(xml).find("firstname:first").text();    
var lastname = $(xml).find("lastname:first").text();
Colin
This works for my case here, thanks!
Josh
+1  A: 

Is there a good way to filter out child tags (especially since I know the parent tag I want to filter)?

Use a CSS child selector to say you only want direct children rather than all descendants.

I'm not sure what ‘xml’ is in your example. If it is an XMLDocument you have got from eg. an AJAX response, you'd say:

var firstname = $(xml).find('userInfo>firstname').text();

On the other hand if it is an XML Element Node for userInfo inside such a document, you'd say:

var firstname = $(xml).find('>firstname').text();

If it's the actual string text of the document above, the second case will seem to work but really it's doing it wrong. Using $(markup) gives you HTML fragments, not XML. Your XML is not valid HTML, and would only work by coincidence.

There isn't a built-in way to create/parse an XML document in jQuery. See eg. http://plugins.jquery.com/project/createXMLDocument for how you might go about doing that, though browser support isn't perfect.

bobince
Is there a more 'proper' way to do this?
Josh
I have the xml from an ajax response. Haven't found a need to use a 3rd party plugin, except for this specific case of child conflict. Thanks for the link, though.
Josh
ah, OK. added some more context to the answer, cheers
bobince