jQuery to get matching nodes in XML
A little background: I was rendering some XML on the page using XSLT, but we decided to make it more interactive and so now I'm doing a jQuery.ajax call to return the XML, and I'm parsing it in JavaScript.
I've been able to extract particular nodes from it using code like
var qpPlanNode = $(xml).find('MyNode');
var qpPlanNum = $(qpPlanNode).children('PLANNUM').text();
And that gets the plan number into qpP开发者_Go百科lanNum. But in that XML I have something like
<xml>
<MyNode>
<PLANNUM>123</PLANNUM>
<SOURCE>
<TYPE>PreTax</TYPE>
<AMOUNT>1234</AMOUNT>
</SOURCE>
<SOURCE>
<TYPE>AfterTax</TYPE>
<AMOUNT>456</AMOUNT>
</SOURCE>
<SOURCE>
<TYPE>PreTax</TYPE>
<AMOUNT>234</AMOUNT>
</SOURCE>
</MyNode>
</xml>
I would like to extract all the SOURCE nodes that have a particular value for TYPE. I can't find a simple jQuery selector that that will do that. In XSLT, I was doing <xsl:variable name="afterTaxSources" select="SOURCE[TYPE = 'AfterTax']"/>
. What's the JQuery equivalent?
I would probably use .parseXML()
var xml = "<xml><MyNode><PLANNUM>123</PLANNUM> <SOURCE> <TYPE>PreTax</TYPE> <AMOUNT>1234</AMOUNT> </SOURCE> <SOURCE> <TYPE>AfterTax</TYPE> <AMOUNT>456</AMOUNT> </SOURCE> <SOURCE> <TYPE>PreTax</TYPE> <AMOUNT>234</AMOUNT> </SOURCE> </MyNode></xml>"
xmlDoc = $.parseXML(xml)
$xml = $(xmlDoc)
$source = $xml.find('TYPE:contains("AfterTax")').parent();
console.log($source);
http://jsfiddle.net/JdZzH/
alternatively
however, i cannot get this to work properly in a live example
console.log($('TYPE:contains("AfterTax")').parent('source'));
should do it, however, I am having trouble getting a jsfiddle to work. it keeps seeing <MyNode>
as the parent, however,
$('TYPE:contains("AfterTax")').css('text-decoration', 'underline');
works as expected, I would try this in something other than jsfiddle.
Utilmately
I think .parseXML() and :contains() are what you are looking for.
I just stumbled on this one, which seems like it is working:
var pretaxSources = $(qpPlanNode).find('SOURCE:has(TYPE:contains("PreTax"))');
Does anybody see any reason why it wouldn't?
Even better, I can combine multiple types using
var pretaxSources = $(qpPlanNode).find('SOURCE:has(TYPE:contains("PreTax"),TYPE:contains("Employee"))');
精彩评论