}
if (trim) {
// concatenate adjacent text nodes together
// so that whitespace trimming works properly
Text lastTextNode = null;
StringBuffer buff = null;
boolean textOnly = true;
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node instanceof Text) {
if (lastTextNode == null) {
lastTextNode = (Text) node;
} else {
if (buff == null) {
buff = new StringBuffer(lastTextNode.getText());
}
buff.append(((Text) node).getText());
}
} else {
if (!textOnly && format.isPadText()) {
// only add the PAD_TEXT if the text itself starts with
// whitespace
char firstChar = 'a';
if (buff != null) {
firstChar = buff.charAt(0);
} else if (lastTextNode != null) {
firstChar = lastTextNode.getText().charAt(0);
}
if (Character.isWhitespace(firstChar)) {
writer.write(PAD_TEXT);
}
}
if (lastTextNode != null) {
if (buff != null) {
writeString(buff.toString());
buff = null;
} else {
writeString(lastTextNode.getText());
}
if (format.isPadText()) {
// only add the PAD_TEXT if the text itself ends
// with whitespace
char lastTextChar = 'a';
if (buff != null) {
lastTextChar = buff.charAt(buff.length() - 1);
} else if (lastTextNode != null) {
String txt = lastTextNode.getText();
lastTextChar = txt.charAt(txt.length() - 1);
}
if (Character.isWhitespace(lastTextChar)) {
writer.write(PAD_TEXT);
}
}
lastTextNode = null;
}
textOnly = false;
writeNode(node);
}
}
if (lastTextNode != null) {
if (!textOnly && format.isPadText()) {
// only add the PAD_TEXT if the text itself starts with
// whitespace
char firstChar = 'a';
if (buff != null) {
firstChar = buff.charAt(0);
} else {
firstChar = lastTextNode.getText().charAt(0);
}
if (Character.isWhitespace(firstChar)) {
writer.write(PAD_TEXT);
}
}
if (buff != null) {
writeString(buff.toString());
buff = null;
} else {
writeString(lastTextNode.getText());
}
lastTextNode = null;
}
} else {
Node lastTextNode = null;
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node instanceof Text) {
writeNode(node);
lastTextNode = node;
} else {
if ((lastTextNode != null) && format.isPadText()) {
// only add the PAD_TEXT if the text itself ends with
// whitespace
String txt = lastTextNode.getText();
char lastTextChar = txt.charAt(txt.length() - 1);
if (Character.isWhitespace(lastTextChar)) {
writer.write(PAD_TEXT);
}