Index

JDOM

XML IO

document from xml String
public Document createDocument(String xml) {
        SAXBuilder builder = new SAXBuilder();
        try {
		return builder.build(new StringReader(xml));
        } catch (Exception e) {
            throw new RuntimeException("Unable to parse xml: " + xml, e);
        }
    }
from JDom element to xml String
private String toXml(Element element, Format format) {
        StringWriter writer = new StringWriter();
        try {

            XMLOutputter outputter = new XMLOutputter(format);
            outputter.output(element, writer);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return writer.getBuffer().toString();
    }

formatting

compact XML Format
Format.getCompactFormat()
human readable XML format
Format.getPrettyFormat()
full formatting example
private String formatXml(String string) {
        try {
            Document document = new SAXBuilder().build(new StringReader(string));
            StringWriter writer = new StringWriter();
            new XMLOutputter(Format.getPrettyFormat()).output(document, writer);
            return writer.getBuffer().toString();

        } catch (Exception e) {
            e.printStackTrace();
            return string;
        }
    }

searching

Search for elements with the given name
@SuppressWarnings("unchecked")
    public static List<Element> getElementsWithName(final Parent parent, final String name) {
        Iterator<Element> iterator = parent.getDescendants(new Filter() {
            @Override
            public boolean matches(Object object) {
                if (object instanceof Element) {
                    Element element = (Element) object;
                    if (element.getName().equalsIgnoreCase(name)) {
                        return true;
                    }
                }
                return false;
            }
        });
        List<Element> result = new ArrayList<Element>();
        while (iterator.hasNext()) {
            result.add(iterator.next());
        }
        return result;
    }
Search for single element with the given name
public static Element getElementWithName(final Parent parent, final String name) {
        List<Element> elements = getElementsWithName(parent, name);
        String failMessage = Str.sub("Expected 1 element with name % found $", name, elements.size());
        Validate.isTrue(elements.size() == 1, failMessage);
        return elements.get(0);
    }