Search code examples
javaparsingstax

Parse special characters in xml stax file


I have the following question:

Original a part of RSS file:

  <item>
      <title> I can get data in tag this </title>
      <description>&lt;p&gt; i don't get data in this &lt;/p&gt;</description></item>

When I read the file using StAX parser the special character '&lt'; . It is automatically converted to '<'. then I cannot get data in the rest of tag "<'description>'

This is my code:

public Feed readFeed() {
Feed feed = null;
try {
  boolean isFeedHeader = true;
  String description = "";
  String title = "";

  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 "title":
        title = getCharacterData(event, eventReader);
        break;
      case "description":
        description = getCharacterData(event, eventReader);
        break;
      }
    } else if (event.isEndElement()) {
      if (event.asEndElement().getName().getLocalPart() == ("item")) {
        FeedMessage message = new FeedMessage();
        message.setDescription(description);
        message.setTitle(title);
        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;} 

I am following the instructions at: http://www.vogella.com/tutorials/RSSFeed/article.html


Solution

  • The tutorial is flawed. It doesn't account for the fact that you could get multiple text events for a single block of text (which tends to happen when you have embedded entities).

    In order to make your life easier, make sure you set the IS_COALESCING property to true on the XMLInputFactory before creating your XMLEventReader (this property forces the reader to combine all adjacent text events into a single event).