import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.List;
public class Test {
public static void main(String[] args) throws DocumentException {
Document document = new SAXReader().read(new File("C:\\Users\\user\\Desktop\\workspace.xml"));
Element root = document.getRootElement();
String attrs = getAttrs(root);
System.out.println("<" + root.getName() + ("".equals(attrs) ? ">" : " " + attrs + ">"));
printElement(root, 1);
System.out.println("</" + root.getName() + ">");
}
private static void printElement(Element root, int marginLevel) {
List<Element> elementList = root.elements();
for (Element element : elementList) {
String attrs = getAttrs(element);
System.out.print(getSpace(marginLevel) + "<" + element.getName() + ("".equals(attrs) ? "" : " " + attrs));
String text = element.getText();
int childLength = element.elements().size();
if (childLength == 0 && text.trim().length() == 0) {
System.out.println("/>");
} else {
System.out.println(">");
if (childLength > 0)
printElement(element, marginLevel + 1);
if (text.trim().length() > 0)
System.out.println(getSpace(marginLevel) + text);
System.out.println(getSpace(marginLevel) + "</" + element.getName() + ">");
}
}
}
private static String getAttrs(Element element) {
List<Attribute> attributes = element.attributes();
if (attributes.size() == 0)
return "";
StringBuilder builder = new StringBuilder(16);
for (Attribute attr : attributes) {
builder.append(attr.getName()).append("=\"").append(attr.getValue()).append("\" ");
}
return builder.substring(0, builder.length() - 1);
}
private static String getSpace(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length * 4; i++) {
builder.append(" ");
}
return builder.toString();
}
}