I am trying to replace every case operator with separate class which will implements method from case. But I did something wrong. As always:D I am getting NullPointerException. I think the problem is in the interface, but I am asking you te be sure.
There's class with switch:
public class RSSFeedParser {
private static final String TITLE = "title";
private static final String DESCRIPTION = "description";
private static final String LANGUAGE = "language";
private static final String COPYRIGHT = "copyright";
private static final String LINK = "link";
private static final String AUTHOR = "author";
private static final String ITEM = "item";
private static final String PUB_DATE = "pubDate";
private static final String GUID = "guid";
private static String description = "";
private static String title = "";
private static String link = "";
private static String language = "";
private static String copyright = "";
private static String author = "";
private static String pubDate = "";
private static String guid = "";
private Feed feed = null;
public InputStream in;
private XMLInputFactory inputFactory = XMLInputFactory.newInstance();
private XMLEventReader eventReader;
final URL url;
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
read().close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() {
try {
boolean isFeedHeader = true;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
String localPart = event.asStartElement().getName().getLocalPart();
switch (localPart) {
case ITEM:
if (isFeedHeader) {
isFeedHeader = false;
feed = new Feed(title, link, description, language, copyright, pubDate);
}
event = eventReader.nextEvent();
break;
case TITLE:
title = getCharacterData(event, eventReader);
eventReader.close();
break;
case DESCRIPTION:
description = getCharacterData(event, eventReader);
eventReader.close();
break;
case LINK:
link = getCharacterData(event, eventReader);
eventReader.close();
break;
case GUID:
guid = getCharacterData(event, eventReader);
eventReader.close();
break;
case LANGUAGE:
language = getCharacterData(event, eventReader);
eventReader.close();
break;
case AUTHOR:
author = getCharacterData(event, eventReader);
eventReader.close();
break;
case PUB_DATE:
pubDate = getCharacterData(event, eventReader);
eventReader.close();
break;
case COPYRIGHT:
copyright = getCharacterData(event, eventReader);
eventReader.close();
break;
}
eventReader.close();
} else if (event.isEndElement()) {
if (event.asEndElement().getName().getLocalPart() == (ITEM)) {
setAllElements();
}
}
And I have done:
public class RSSFeedParser {
public static final String ITEM = "item";
public static String description = "";
public static String title = "";
public static String link = "";
public static String language = "";
public static String copyright = "";
public static String author = "";
public static String pubDate = "";
public static String guid = "";
public Feed feed;
public boolean isFeedHeader;
TITLE tytul = new TITLE();
AUTHOR autor = new AUTHOR();
COPYRIGHT prawa = new COPYRIGHT();
DESCRIPTION opis = new DESCRIPTION();
GUID identyfikacja = new GUID();
LANGUAGE jezyk = new LANGUAGE();
LINK linskon = new LINK();
PUB_DATE publikajca = new PUB_DATE();
ITEM itemson = new ITEM();
public InputStream in;
public XMLInputFactory inputFactory = XMLInputFactory.newInstance();
public XMLEventReader eventReader;
public XMLEvent event;
final URL url;
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
event = eventReader.nextEvent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() throws XMLStreamException {
try {
isFeedHeader = true;
while (eventReader.hasNext()) {
itemson.feedData();
tytul.feedData();
opis.feedData();
linskon.feedData();
identyfikacja.feedData();
jezyk.feedData();
autor.feedData();
publikajca.feedData();
prawa.feedData();
eventReader.close();
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;}
And interface:
public interface Case {
RSSFeedParser rss = null; // the reason why I get NullPointerException, right? But how else could I get into the fields of the this class without constructing its object?
void feedData() throws XMLStreamException;
One of few classes:
public class COPYRIGHT implements Case {
#Override
public void feedData() throws XMLStreamException {
rss.copyright = rss.getCharacterData(rss.event, rss.eventReader);
rss.eventReader.close();
}
Exception in thread "main" java.lang.NullPointerException
at ITEM.feedData(ITEM.java:9)
at RSSFeedParser.readFeed(RSSFeedParser.java:61)
at ReadTest.printRSS(ReadTest.java:70)
at ReadTest.MENU(ReadTest.java:33)
at ReadTest.main(ReadTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Related
I created XML parsing RSS reader,but it is only reading the last 3 nodes (which is title,link and description ).i want to know which lines of code making this trick(i mean reading the last nodes).if i want to read the first three nodes from this rss site,what i should i actually do ?
i am a nuwbie . can anyone post the answer as code?
public class HandleXML {
private String title = "title";
private String link = "link";
private String description = "description";
private String title1 = "title";
private String link1 = "link";
private String description1 = "description";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(String url){
this.urlString = url;
}
public String getTitle(){
return title;
}
public String getLink(){
return link;
}
public String getDescription(){
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
}
else if(name.equals("link")){
link = text;
}
else if(name.equals("description")){
description = text;
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e) {
}
}
});
thread.start();
}
}
It is this part of the code that is responsible to read the elements you mentioned above .
if(name.equals("title")){
title = text;
}
else if(name.equals("link")){
link = text;
}
else if(name.equals("description")){
description = text;
}
else{
// Write similar conditions for the other tags that you want to parse.
}
You are using a while loop in order to process the document.
Within that loop your code reads all the title, link and description nodes.
The problem is that it overrides the variables every time, hence what you get is the last title, link and description.
If you would like to read only the firs title, link and description you could do something like:
Initialise variables like this:
private String title;
private String link;
private String description;
Than:
if(name.equals("title") && title != null){
title = text;
}
else if(name.equals("link") && link != null){
link = text;
}
else if(name.equals("description") && description != null){
description = text;
}
EDIT (try this, warning: I haven't tested it)
public class HandleXML {
public volatile boolean parsingComplete = true;
private String title;
private String link;
private String description;
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public HandleXML(String url) {
this.urlString = url;
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
public String getDescription() {
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("title") && title != null) {
title = text;
}
else if (name.equals("link") && link != null) {
link = text;
}
else if (name.equals("description") && description != null) {
description = text;
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e) {
// TODO: 27/07/2017 handle exception
}
}
});
thread.start();
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to parse xml data in android. I have seen this project: here from github which teaches how to parse xml data in listbox. However, I want to get xml data to different strings. Although, I have used pretty much the same code as in the github project but I only get error and the app stops responding.
Code:
public class Main extends Fragment {
android.view.View myview;
EditText number;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myview = inflater.inflate(R.layout.fragment_screen, container, false);
number = (EditText) myview.findViewById(R.id.number);
XmlParser par = new XmlParser();
number.setText(par.getStackSitesFromFile(getActivity().getBaseContext())
.get(0).getLink()); **Error here**
return myview;
}
}
XmlParser.java
public class XmlParser {
static final String KEY_SITE = "rate";
static final String KEY_NAME = "Name";
static final String KEY_LINK = "Rate";
static final String KEY_ABOUT = "Date";
static final String KEY_IMAGE_URL = "Time";
public static List<HandleXML> getStackSitesFromFile(Context ctx) {
// List of StackSites that we will return
List<HandleXML> stackSites;
stackSites = new ArrayList<HandleXML>();
// temp holder for current StackSite while parsing
HandleXML curStackSite = null;
// temp holder for current text value while parsing
String curText = "";
try {
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("/sdcard/rates.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equals("test")) {
curStackSite = new HandleXML();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("test")) {
stackSites.add(curStackSite);
} else if (tagname.equalsIgnoreCase(KEY_NAME)) {
curStackSite.setName(curText);
} else if (tagname.equals("Rate")) {
curStackSite.setLink(curText);
} else if (tagname.equalsIgnoreCase(KEY_ABOUT)) {
curStackSite.setAbout(curText);
} else if (tagname.equalsIgnoreCase(KEY_IMAGE_URL)) {
curStackSite.setImgUrl(curText);
}
break;
default:
break;
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return stackSites;
}
}
And finally, HandleXml.java
public class HandleXML {
private String name;
private String rate;
private String date;
private String time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return rate;
}
public void setLink(String rate) {
this.rate = rate;
}
public String getAbout() {
return date;
}
public void setAbout(String date) {
this.date = date;
}
public String getImgUrl() {
return time;
}
public void setImgUrl(String time) {
this.time = time;
}
#Override
public String toString() {
return name + rate;
}
}
Xml File:
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2016-09-07T05:50:08Z" yahoo:lang="en-US">
<results>
<test>
<Name>EUR/USD</Name>
<Rate>1.1251</Rate>
<Date>9/7/2016</Date>
<Time>0:56am</Time>
</test>
<test>
<Name>EUR/USD</Name>
<Rate>1.1253</Rate>
<Date>9/7/2016</Date>
<Time>0:56am</Time>
</test>
</results>
</query>
The error is in the first fragment of code in: number.setText(par.getStackSitesFromFile(getActivity().getBaseContext()).get(0).getLink());
The arraylist returns empty because FileInputStream fis is set to open a file which contains path separator (/) , and it causes
java.lang.IllegalArgumentException: File /sdcard/rates.xml contains a path separator
. You have to use
FileInputStream fis = new FileInputStream (new File("/sdcard/rates.xml")); instead. Do not forget to close fis by fis.close();
Final code for XmlParser will be:
public class XmlParser {
static final String KEY_SITE = "rate";
static final String KEY_NAME = "Name";
static final String KEY_LINK = "Rate";
static final String KEY_ABOUT = "Date";
static final String KEY_IMAGE_URL = "Time";
FileInputStream fis;
public static List<HandleXML> getStackSitesFromFile() {
// List of StackSites that we will return
List<HandleXML> stackSites;
stackSites = new ArrayList<HandleXML>();
// temp holder for current StackSite while parsing
HandleXML curStackSite = null;
// temp holder for current text value while parsing
String curText = "";
try {
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
fis = new FileInputStream(new File("/sdcard/rates.xml"));
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equals("test")) {
curStackSite = new HandleXML();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("test")) {
stackSites.add(curStackSite);
} else if (tagname.equalsIgnoreCase(KEY_NAME)) {
curStackSite.setName(curText);
} else if (tagname.equals("Rate")) {
curStackSite.setLink(curText);
} else if (tagname.equalsIgnoreCase(KEY_ABOUT)) {
curStackSite.setAbout(curText);
} else if (tagname.equalsIgnoreCase(KEY_IMAGE_URL)) {
curStackSite.setImgUrl(curText);
}
break;
default:
break;
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
}catch(Exception e){
Log.i("Problem closing", "Closing fis");
}
// return the populated list.
return stackSites;
}
}
And then set number.setText() like that: number.setText(par.getStackSitesFromFile().get(0).getLink());
I have used the code below. I do not have a problem with other tags but I can not get contents of description. I think there may be a problem with character set of news feed. There are Turkish characters and they may need to handled with a unicode reader. But I do not know how to achieve that.
public class NewsFeed {
final URL url;
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String CHANNEL = "channel";
static final String LANGUAGE = "language";
static final String COPYRIGHT = "copyright";
static final String LINK = "link";
static final String AUTHOR = "author";
static final String ITEM = "item";
static final String PUB_DATE = "pubDate";
static final String GUID = "guid";
static final String IMAGE = "image";
NewsFeed() throws XMLStreamException, MalformedURLException {
url = new URL("http://www.haberturk.com/rss/manset.xml");
boolean isFeedHeader = true;
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = read();
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
String localPart = event.asStartElement().getName()
.getLocalPart();
switch (localPart) {
case ITEM:
if (isFeedHeader) {
isFeedHeader = false;
}
event = eventReader.nextEvent();
break;
case TITLE:
String title = getCharacterData(event, eventReader);
System.out.println(title + "////");
break;
case DESCRIPTION:
String description = getCharacterData(event, eventReader);
System.out.println(description);
break;
case LINK:
String link = getCharacterData(event, eventReader);
System.out.println(link);
}
}
}
}
private InputStream read() {
try {
return url.openStream();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private String getCharacterData(XMLEvent event, XMLEventReader eventReader)
throws XMLStreamException {
String result = "";
event = eventReader.nextEvent();
if (event instanceof Characters) {
result = event.asCharacters().getData();
}
return result;
}
public static void main(String[] args) throws MalformedURLException, XMLStreamException {
new NewsFeed();
}
}
Why in the while block you have: event = eventReader.nextEvent();
while () {
event = eventReader.nextEvent();
.
.
.
}
And you have another call of event = eventReader.nextEvent();
within method getCharacterData.
event = eventReader.nextEvent();
if (event instanceof Characters) {
result = event.asCharacters().getData();
}
Probably that's the problem!
Hope this helps!
try this:
URL url = new URL("myURL");
InputStream is=url.openStream();
BufferedReader brd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader = factory.createXMLEventReader(brd);
I am trying change my RSS Reader code. I have something like this:
public class RSSFeedParser {
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String CHANNEL = "channel";
static final String LANGUAGE = "language";
static final String COPYRIGHT = "copyright";
static final String LINK = "link";
static final String AUTHOR = "author";
static final String ITEM = "item";
static final String PUB_DATE = "pubDate";
static final String GUID = "guid";
public InputStream in = read();
private XMLInputFactory inputFactory = XMLInputFactory.newInstance();
private XMLEventReader eventReader;
final URL url;
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
eventReader = inputFactory.createXMLEventReader(in);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() {
Feed feed = null;
try {
boolean isFeedHeader = true;
String description = "";
String title = "";
String link = "";
String language = "";
String copyright = "";
String author = "";
String pubDate = "";
String guid = "";
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
String localPart = event.asStartElement().getName().getLocalPart();
switch (localPart) {
case ITEM:
if (isFeedHeader) {
isFeedHeader = false;
feed = new Feed(title, link, description, language, copyright, pubDate);
}
event = eventReader.nextEvent();
break;
case TITLE:
title = getCharacterData(event, eventReader);
break;
case DESCRIPTION:
description = getCharacterData(event, eventReader);
break;
case LINK:
link = getCharacterData(event, eventReader);
break;
case GUID:
guid = getCharacterData(event, eventReader);
break;
case LANGUAGE:
language = getCharacterData(event, eventReader);
break;
case AUTHOR:
author = getCharacterData(event, eventReader);
break;
case PUB_DATE:
pubDate = getCharacterData(event, eventReader);
break;
case COPYRIGHT:
copyright = getCharacterData(event, eventReader);
break;
}
}
else if(event.isEndElement()) {
if (event.asEndElement().getName().getLocalPart() == (ITEM)) {
FeedMessage message = new FeedMessage();
message.setAuthor(author);
message.setDescription(description);
message.setGuid(guid);
message.setLink(link);
message.setTitle(title);
feed.getMessages().add(message);
}
}
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;
}
private InputStream read(){
try{
return url.openStream();
}catch (IOException e){
throw new RuntimeException(e);
}
}
private String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException {
String results="";
event = eventReader.nextEvent();
if(event instanceof Characters){
results = event.asCharacters().getData();
}
return results;
}
And main:
public static void main(String[] args) {
RSSFeedParser parser = new RSSFeedParser("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml");
Feed feed = parser.readFeed();
System.out.println(feed);
for (FeedMessage message : feed.getMessages()) {
System.out.println(message);
RSSFeedWriter writer = new RSSFeedWriter(feed, "articles.rss");
try {
writer.write();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I get NullPointerException in
public InputStream in = read();
return url.openStream();
RSSFeedParser parser = new RSSFeedParser("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml");
What's wrong with this code? Everything was working when the InputStream, XMLEventReader and XMLInputFactory was in separate class.
You are calling the read() method before the URL object is initialized. Try something like this:
public InputStream in;
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Also, It is good practice to close resources after use (streams & readers).
I am trying to display a text from a news in any category of a newspaper. I use RSS of this newspaper. However when I run the code, sometimes I get the exception message in the above, sometimes it works correctly. Here is my RSS Parser code:
And the rss page that I use is:
RSSFeedParser parser = new RSSFeedParser("http://www.cumhuriyet.com.tr/rss/5");
Feed feed = parser.readFeed();
The RSS parser code:
package main;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
public class RSSFeedParser {
static final String TITLE = "title";
static final String DESCRIPTION = "description";
static final String CHANNEL = "channel";
static final String LANGUAGE = "language";
static final String COPYRIGHT = "copyright";
static final String LINK = "link";
static final String AUTHOR = "author";
static final String ITEM = "item";
static final String PUB_DATE = "pubDate";
static final String GUID = "guid";
static final String IMG = "img";
final URL url;
public RSSFeedParser(String feedUrl) {
try {
this.url = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() {
Feed feed = null;
try {
boolean isFeedHeader = true;
// Set header values intial to the empty string
String description = "";
String title = "";
String link = "";
String language = "";
String copyright = "";
String author = "";
String pubDate = "";
String guid = "";
String img = "";
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = read();
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// read the XML document
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
String localPart = event.asStartElement().getName()
.getLocalPart();
switch (localPart) {
case ITEM:
if (isFeedHeader) {
isFeedHeader = false;
feed = new Feed(title, link, description, language,
copyright, pubDate);
}
event = eventReader.nextEvent();
break;
case TITLE:
title = getCharacterData(event, eventReader);
break;
case DESCRIPTION:
description = getCharacterData(event, eventReader);
break;
case LINK:
link = getCharacterData(event, eventReader);
break;
case GUID:
guid = getCharacterData(event, eventReader);
break;
case LANGUAGE:
language = getCharacterData(event, eventReader);
break;
case AUTHOR:
author = getCharacterData(event, eventReader);
break;
case PUB_DATE:
pubDate = getCharacterData(event, eventReader);
break;
case COPYRIGHT:
copyright = getCharacterData(event, eventReader);
break;
}
} else if (event.isEndElement()) {
if (event.asEndElement().getName().getLocalPart() == (ITEM)) {
FeedMessage message = new FeedMessage();
message.setDescription(description);
message.setPubDate(pubDate);
message.setLink(link);
message.setTitle(title);
message.setImg(img);
feed.getMessages().add(message);
event = eventReader.nextEvent();
continue;
}
}
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;
}
private String getCharacterData(XMLEvent event, XMLEventReader eventReader)
throws XMLStreamException {
String result = "";
event = eventReader.nextEvent();
if (event instanceof Characters) {
result = event.asCharacters().getData();
}
return result;
}
private InputStream read() {
try {
return url.openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Exception message is:
Exception in thread "main" java.lang.RuntimeException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,3]
Message: The element type "meta" must be terminated by the matching end-tag "</meta>".
at main.RSSFeedParser.readFeed(RSSFeedParser.java:112)
at cumhuriyet.Dunya.cumDunya(Dunya.java:32)
at automation.ServerInteraction.main(ServerInteraction.java:83)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,3]
Message: The element type "meta" must be terminated by the matching end-tag "</meta>".
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(Unknown Source)
at main.RSSFeedParser.readFeed(RSSFeedParser.java:58)
... 2 more
That looks like it is a live document; i.e. one that changes fairly frequently. There is also no sign of a tag in it.
I can think of two explanations for what is happening:
Sometimes the document is being generated or created incorrectly.
Sometimes you are getting an HTML error page instead of the document
you are expecting, and the XML parser can't cope with a tag in
the HTML's .
To track this down, you are going to have to capture the precise input that is causing the parse to fail.