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:
parent
8a2a384dfa
commit
05c9a4c92a
|
@ -28,11 +28,15 @@ public class SaxParserMain {
|
||||||
private static final String CONTENT = "content";
|
private static final String CONTENT = "content";
|
||||||
|
|
||||||
private Baeldung website;
|
private Baeldung website;
|
||||||
private String elementValue;
|
private StringBuilder elementValue;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void characters(char[] ch, int start, int length) throws SAXException {
|
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
|
@Override
|
||||||
|
@ -48,6 +52,13 @@ public class SaxParserMain {
|
||||||
break;
|
break;
|
||||||
case ARTICLE:
|
case ARTICLE:
|
||||||
website.getArticleList().add(new BaeldungArticle());
|
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 {
|
public void endElement(String uri, String localName, String qName) throws SAXException {
|
||||||
switch (qName) {
|
switch (qName) {
|
||||||
case TITLE:
|
case TITLE:
|
||||||
latestArticle().setTitle(elementValue);
|
latestArticle().setTitle(elementValue.toString());
|
||||||
break;
|
break;
|
||||||
case CONTENT:
|
case CONTENT:
|
||||||
latestArticle().setContent(elementValue);
|
latestArticle().setContent(elementValue.toString());
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue