views:

160

answers:

3

I'm having trouble accessing only one XML element that has the same name as other elements (i this case, the tag "name"). How do I access ONLY the "wantedName" below using jQuery?

<sample>
<input>
    <value>0.2</value>
    <name>varName</name>  
</input> 
<name>wantedName</name> 
<output> 
    <value>4</value> 
    <name>varName2</name> 
</output>
</sample>

Using $(xml).find("name") returns an array containing [varName, wantedName, varName2]. Unfortunately I can't just resort to accessing the 1st index because the xml is dynamic, so I'm not sure at which index the "wantedName" will be.

I'd like to access "wantedName" by doing something like "if this has an immediate parent named <sample>, get it, otherwise ignore".

+1  A: 

Assuming the structure of the xml always looks like the example given (where name is directly after the input tag), I think this might work

$(xml).find("input + name");
T B
fantastic! this was the only one that worked. thanks a lot T B
sheldon
A: 

Presumably you want to retrieve any name tags that are children of sample, but not those that are children of input or any other tag?

If so, this should work:

$(xml).find("sample > name");

Rob Knight
This was my first answer and as redsquare pointed out, this wont work since sample is the root of the xml document. Paste this in firebug and you will see that know element is returned: var $xml = $("<sample><input1><value>0.2</value><name>varName</name></input1><name>wantedName</name><output><value>4</value><name>varName2</name> </output></sample>");$xml.find("sample > name");
T B
A: 

$(xml).find("input > name").text() should work just fine, assuming you're working with xml as part of the dom, and not just a string. It's because 'input' is a tag name in html.

If you're working with a string, here is a parseXml function I found quickly, and tested in FF 3. So, parse your string, then traverse it via jquery.

function parseXML(xml) {
    if (window.ActiveXObject && window.GetObject) {
        var dom = new ActiveXObject('Microsoft.XMLDOM');
        dom.loadXML(xml);
        return dom;
    }
    if (window.DOMParser)
        return new DOMParser().parseFromString(xml, 'text/xml');
    throw new Error('No XML parser available');
}

Edit

This will also work without parsing as xml, assuming that your xml is unchanged.

$(xml).find("name:first").text();
ScottE
$(xml).find("name:first").text() instead returned "varName", and your first solution ( $(xml).find("input > name").text() returned undefined :(
sheldon
Whoops, I thought you wanted the 'name' under the input element. The first example had to be parsed as xml first.
ScottE