Yashpal
Yashpal

Reputation: 111

how to fetch text from cdata section of xml files

<text>
    <![CDATA[
        <img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg" width="600" />
        <img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_2.jpg" width="600" />
    ]]>
</text>
</description>

this is my rss feed i want to fetch description from this by using sax parser .but am unable to do this so please help and suggest me all the possible way to do this thanx in advance

Upvotes: 2

Views: 1222

Answers (2)

Gene Bushuyev
Gene Bushuyev

Reputation: 5538

Don't know which language you want to use for parsing. Since I'm working only in C++, here is a parser for CDATA written using AXE parser generator:

std::string cdata;
auto cdata_rule = "<![CDATA[" & *(axe::r_any() - "]]>") >> cdata & "]]>";
// now do the parsing of input
cdata_rule(input.begin(), input.end());

// parse img elements
std::vector<std::string> sources; // all your img sources will be here
auto src_rule = "src=\"" & *(r_any() - '"') >> r_push_back(sources) & '"';
auto ignore = *(r_any() - "src=");
auto tail = *(r_any() - "/>") & "/>" & *r_any(" \t\n");
auto img_rule = *("<img & ignore & src_rule & tail);
auto result = img_rule(cdata.begin(), cdata.end());

Disclaimer: I didn't test the code above, minor errors are possible.

Upvotes: 0

Tobias
Tobias

Reputation: 4292

CDATA just tells the parser not to treat angle brackets as XML tags. You get the content just like any other character data inside a tag. Since you didn't mention anything here's Python:

import xml.sax
from cStringIO import StringIO

class Handler(xml.sax.handler.ContentHandler):
    def characters(self, content):
        print content

rss = '<text><![CDATA[<img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg" width="600" /><img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_2.jpg" width="600" />]]></text>'

xml.sax.parse(StringIO(rss), Handler())

Upvotes: 2

Related Questions