JDOM


load an occasional java string as xml in jdom objects:
private void addAsJDOM(Element parent, String s) {

        s = "<p>" + s + "</p>"; //as root element of the string

        SAXBuilder builder = new SAXBuilder();
        Reader reader = new StringReader(s);
        Document stringDoc = null;
        try {
            stringDoc = builder.build(reader);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        parent.addContent((Content) stringDoc.getRootElement().clone());
    }


private boolean checkURITag(Document doc) {
        Element root = doc.getRootElement();
        Iterator iter = root.getDescendants();
        Element element;
        Object obj;

        while (iter.hasNext()) {
            obj = iter.next();
            if (obj instanceof Element) {
                element = (Element) obj;
                if (element.getName().equals("uri")) {
                    return true;
                }
            }
        }
        return false;
    }

-----------------------------------------------------------------------------------------------------------------------------------------------------------

private Document readFile(File xmlFile) {
        SAXBuilder builder;
        boolean expandEntities = true;
        Document doc = null;

        // Create an instance of the tester and test
        try {
            builder = new SAXBuilder();
            builder.setExpandEntities(expandEntities);

            doc = builder.build(xmlFile);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;

    }


private void writeFile(Document document, String outFile) {
        Format format = Format.getPrettyFormat();
        // format.setOmitDeclaration(true);
        format.setEncoding("UTF-8");
        XMLOutputter outputter = new XMLOutputter(format);
        FileOutputStream out;
        try {
            out = new FileOutputStream(outFile);

            outputter.output(document, out);
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

Comments