Reputation: 189
I am querying the Microsoft Office SharePoint Server Search Service to write some results into a web part. I have the query working correctly but am having some trouble parsing the xml response via JQuery.
Below is the XML response :
<document>
<properties>
<Property>
<Name>p1</Name>
<Type>String</Type>
<Value>blue</Value>
</Property>
<Property>
<Name>title</Name>
<Type>string</Type>
<Value>titreA</Value>
</Property>
</properties>
</document>
<document>
<properties>
<Property>
<Name>p1</Name>
<Type>String</Type>
<Value>blue</Value>
</Property>
<Property>
<Name>title</Name>
<Type>string</Type>
<Value>titreB</Value>
</Property>
</properties>
</document>
<document>
<properties>
<Property>
<Name>p1</Name>
<Type>String</Type>
<Value>green</Value>
</Property>
<Property>
<Name>title</Name>
<Type>string</Type>
<Value>titreC</Value>
</Property>
</properties>
</document>
<document>
<properties>
<Property>
<Name>p1</Name>
<Type>String</Type>
<Value>red</Value>
</Property>
<Property>
<Name>title</Name>
<Type>string</Type>
<Value>titreD</Value>
</Property>
</properties>
</document>
How can i retrieve p1 value, and number of occurence of this value ? Like this : blue(2), green(1), red(1)
Upvotes: 2
Views: 260
Reputation: 227310
XML data can be 'parsed' using jQuery's methods just like HTML. Assuming data
is the XML data.
var name = 'p1';
$data = $(data);
$p1 = $data.find('Name:contains("'+name+'")').parent('Property');
p1Value = $p1.map(function(i,v){
return $(v).children('Value').text();
}).get();
alert(p1Value);
p1Value is an array of values that have a name of 'p1'.
p1Value[0]
is equal to 'blue'.
If you also want the number of occurrences, you can do this.
var name = 'p1';
$data = $(data);
$p1 = $data.find('Name:contains("'+name+'")').parent('Property');
p1Values = {};
$p1.each(function(i,v){
var val = $(v).children('Value').text();
if(p1Values.hasOwnProperty(val)){
p1Values[val]++;
}
else{
p1Values[val] = 1;
}
});
p1Values is an object with the value as the property name, and the occurrences as the property value.
p1Value['blue']
is equal to 2.
Upvotes: 2
Reputation: 14776
Assuming you have this in something like
.ajax(
// calling code here
success: function(data, status, xhr) {
var jqData = $(data);
var countMap = {};
jqData.find("Value").each(function() {
// filter for only P1
var jqThis = $(this);
if(jqThis.parent().find("Name").text == "p1") {
if(countMap[jqThis.text]) {
countMap[jqThix.text]++;
} else {
countMap[jqThis.text] = 1;
}
}
});
// From here countMap should contain the value in Value for each p1 as a key
// and a count of occurrences as a value
}
);
Upvotes: 0