From 935465a11b7376be29c6967b5be5c9fde7a1e51a Mon Sep 17 00:00:00 2001 From: Florian Schmaus Date: Wed, 4 Sep 2019 09:47:29 +0200 Subject: [PATCH] Remove duplicate code in XmlStringBuilder --- .../smack/util/XmlStringBuilder.java | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java b/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java index e59e8e423..8724eb8b5 100644 --- a/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java +++ b/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java @@ -591,21 +591,10 @@ public class XmlStringBuilder implements Appendable, CharSequence, Element { * @throws IOException if an I/O error occured. */ public void write(Writer writer, String enclosingNamespace) throws IOException { - for (CharSequence csq : sb.getAsList()) { - if (csq instanceof XmlStringBuilder) { - ((XmlStringBuilder) csq).write(writer, enclosingNamespace); - } - else if (csq instanceof XmlNsAttribute) { - XmlNsAttribute xmlNsAttribute = (XmlNsAttribute) csq; - if (!xmlNsAttribute.value.equals(enclosingNamespace)) { - writer.write(xmlNsAttribute.toString()); - enclosingNamespace = xmlNsAttribute.value; - } - } - else { - writer.write(csq.toString()); - } - } + XmlEnvironment enclosingXmlEnvironment = XmlEnvironment.builder() + .withNamespace(enclosingNamespace) + .build(); + appendXmlTo(writer, enclosingXmlEnvironment); } public Iterator getCharSequenceIterator() { @@ -615,14 +604,19 @@ public class XmlStringBuilder implements Appendable, CharSequence, Element { @Override public CharSequence toXML(XmlEnvironment enclosingXmlEnvironment) { StringBuilder res = new StringBuilder(); - appendXmlTo(res, enclosingXmlEnvironment); + try { + appendXmlTo(res, enclosingXmlEnvironment); + } catch (IOException e) { + // Should never happen. + throw new AssertionError(e); + } return res; } - private void appendXmlTo(StringBuilder res, XmlEnvironment enclosingXmlEnvironment) { + private void appendXmlTo(Appendable appendable, XmlEnvironment enclosingXmlEnvironment) throws IOException { for (CharSequence csq : sb.getAsList()) { if (csq instanceof XmlStringBuilder) { - ((XmlStringBuilder) csq).appendXmlTo(res, enclosingXmlEnvironment); + ((XmlStringBuilder) csq).appendXmlTo(appendable, enclosingXmlEnvironment); } else if (csq instanceof XmlNsAttribute) { XmlNsAttribute xmlNsAttribute = (XmlNsAttribute) csq; @@ -632,7 +626,7 @@ public class XmlStringBuilder implements Appendable, CharSequence, Element { } } else { - res.append(csq); + appendable.append(csq); } } }