characters(...) fills StringBuilder instead of String

I startet to implement an XML parser from this tutorial and ran into a problem with empty elements, e.g. <elem></elem>. I found this SO post (https://stackoverflow.com/questions/44570604/sax-parser-is-not-working-properly-when-xml-input-is-given-as-stream-and-some-xm) and realised, that characters(...) can be called zero or multiple times, so one should fixed it conceptually by using a StringBuffer or StringBuilder.
This commit is contained in:
Martin Porsch 2021-02-18 10:39:41 +01:00 committed by GitHub
parent 8a2a384dfa
commit 05c9a4c92a
1 changed files with 15 additions and 4 deletions

View File

@ -28,11 +28,15 @@ public class SaxParserMain {
private static final String CONTENT = "content";
private Baeldung website;
private String elementValue;
private StringBuilder elementValue;
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
elementValue = new String(ch, start, length);
if (elementValue == null) {
elementValue = new StringBuilder();
} else {
elementValue.append(ch, start, length);
}
}
@Override
@ -48,6 +52,13 @@ public class SaxParserMain {
break;
case ARTICLE:
website.getArticleList().add(new BaeldungArticle());
break;
case TITLE:
elementValue = new StringBuilder();
break;
case CONTENT:
elementValue = new StringBuilder();
break;
}
}
@ -55,10 +66,10 @@ public class SaxParserMain {
public void endElement(String uri, String localName, String qName) throws SAXException {
switch (qName) {
case TITLE:
latestArticle().setTitle(elementValue);
latestArticle().setTitle(elementValue.toString());
break;
case CONTENT:
latestArticle().setContent(elementValue);
latestArticle().setContent(elementValue.toString());
break;
}
}