SV: [jdom-interest] encoding problem converting XML document to string

Per Norrman pernorrman at telia.com
Thu Nov 6 08:19:17 PST 2003


Hi,

you can always try  processing the JDOM document and remove
unwanted "empty" text nodes. I don't know which version is included
in JBuilder, but it should be available in META-INF/info.xml in the
jdom.jar.

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

import java.io.File;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * @author Per Norrman
 *
 */
public class JDOMNormalizer {

	public void normalize(Document doc) {
		normalize(doc.getRootElement());
	}

	public void normalize(Element element) {
		for (Iterator i = element.getContent().iterator();
i.hasNext();) {
			Object node = i.next();
            if (node instanceof Text) {
                Text textNode = (Text) node;
		    // textNode.getTextNormailze() should also work
                if (textNode.getTextTrim().length() == 0) {
                    i.remove(); 
                }
            } else if (node instanceof Element) {
                normalize((Element)node);
            }
		}
	}

	public static void main(String[] args) {
        try {
			Document doc = new SAXBuilder().build(new
File(args[0]));
            new JDOMNormalizer().normalize(doc);
            XMLOutputter out = new XMLOutputter();
            String xml = out.outputString(doc);
            System.out.println(xml);
		} catch (Exception e) {
            e.printStackTrace();
		}
	}
}
-----------------------------------------------

Hope this helps,

/pmn




More information about the jdom-interest mailing list