开发者

how to fetch text from cdata section of xml files

开发者 https://www.devze.com 2023-03-09 20:02 出处:网络
<text> <![CDATA[ <img style=\"vertical-align: middle;\" src=\"http://www.bjp.org/images/stories/economic_cell_1.jpg开发者_如何学Go\" width=\"600\" />
<text>
    <![CDATA[
        <img style="vertical-align: middle;" src="http://www.bjp.org/images/stories/economic_cell_1.jpg开发者_如何学Go" 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


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())


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号