开发者

Why does my XML parser only returns one string, instead of multiple ones?

开发者 https://www.devze.com 2023-03-27 20:29 出处:网络
I got a problem regarding parsing XML data. I have divided my program into 3 different java files, each containing a class. One of them is rssparser.java. This file holds a function called iterateRSSF

I got a problem regarding parsing XML data. I have divided my program into 3 different java files, each containing a class. One of them is rssparser.java. This file holds a function called iterateRSSFeed(String URL), this function returns a string containing the parsed description tag. In my main.java files where my main method is, I call this iterateRSSFeed function this way:

rssparser r = new rssparser();
String description = r.iterateRSSFeed();

And then I am planning to add this String to a JLabel, this way:

JLabel news = new JLabel(description);

which obviously works great, my program runs. BUT there are more description tags in my XML file, the JLabel only co开发者_运维百科ntains one(1) parsed description tag. I should say that my return statement in the iterateRSSFeed function is "packed" in a for-loop, which in my head should return all of the description tags. But no.

Please ask if something is uncleared or showing of the source code is a better way to provide a solution to my answer. Thanks in advance! :)


When Java executes a return statement, it will leave the method, and not continue running the loop.

If you want to return multiple values from a method, you have to put them in some object grouping them together. Normally one would use a List<String> as return type.

Then your loop will fill the list, and the return statement (after the loop) can return the whole list at once.

If you want to have one large string instead of multiple ones, you'll have to merge them into one. The easiest would be to simply use the .toString() method on the list, this will give (if you are using the default list implementations) something like [element1, element2, element3].

If you don't like the [,], you could simply concatenate them:

List<String> list = r.iterateRSSFeed();
StringBuilder b = new StringBuilder();
for(String s : list) {
   b.append(s);
}
String description = b.toString();

This will give element1element2element3.

As Java's JLabel has some rudimentary HTML support, you could also use this to format your list as a list:

List<String> list = r.iterateRSSFeed();
StringBuilder b = new StringBuilder();
b.append("<html><ul>");
for(String s : list) {
   b.append("<li>");
   b.append(s);
   b.append("</li>");
}
b.append("</ul>");
String description = b.toString();

The result will be <html><ul><li>element1</li><li>element2</li><li>element3</li></ul>, which will be formatted by the JLabel as something like this:

  • element1
  • element2
  • element3
0

精彩评论

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

关注公众号