Reputation: 9396
Here is my xml:
<?xml version='1.0'?>
<rss version="2.0">
<channel>
<title>Some Title</title>
<pubDate>1/1/17 00:00:00</pubDate>
<generator>SomeOne</generator>
<item>
<title>
Some Item Title 1
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat1</category>
<category>Cat2</category>
</item>
<item>
<title>
Some Item Title 2
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat2</category>
</item>
<item>
<title>
Some Item Title 3
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat1</category>
</item>
....
....
....
</channel>
</rss>
I am using this jQuery
code to remove the parents:
var myCat = 'Cat1';
rss.find('item').find('category').filter(':not(:contains('+ myCat +'))').parent().remove();
Now the problem is, As you can see in my provided xml that. Single, <item>
contains 2 <category>
and one of those is a match for myCat
but that <item>
is still removed, whilst it shouldn't be. jsFiddle
P.S. From given example, only the 2nd <item>
should be removed.
Upvotes: 2
Views: 38
Reputation: 12880
You should loop over your items and see if each one contains your cat:
var str = `<?xml version='1.0'?>
<rss version="2.0">
<channel>
<title>Some Title</title>
<pubDate>1/1/17 00:00:00</pubDate>
<generator>SomeOne</generator>
<item>
<title>
Some Item Title 1
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat1</category>
<category>Cat2</category>
</item>
<item>
<title>
Some Item Title 2
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat2</category>
</item>
<item>
<title>
Some Item Title 3
</title>
<link>http://example.org</link>
<description>
Lorem ipsum ...
</description>
<pubDate>1/1/17 00:00:00</pubDate>
<category>Cat1</category>
</item>
</channel>
</rss>`;
var rss = $.parseXML(str);
rss = $(rss);
var myCat = 'Cat1';
rss.find('item').each(function(){
if($(this).find('category:contains('+ myCat +')').length == 0){
$(this).remove();
}
});
console.log(rss.find('item').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1