// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.StringReader;
//import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.apache.xpath.XPathAPI;
//import org.apache.xml.serialize.OutputFormat;
//import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
//

public class XmlManip {
    public static void main(String[] args) throws Exception {
        String s="<xml><node1>bla</node1><node2>T</node2><node3>værdi</node3><node4>værdi</node4><node5>værdi</node5><node6>værdi</node6></xml>";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(s)));
        if(XPathAPI.selectSingleNode(doc.getDocumentElement(), "//xml/node2/text()").getNodeValue().equals("F")) {
            doc.getDocumentElement().removeChild(XPathAPI.selectSingleNode(doc.getDocumentElement(), "//xml/node3"));
            doc.getDocumentElement().removeChild(XPathAPI.selectSingleNode(doc.getDocumentElement(), "//xml/node4"));
            doc.getDocumentElement().removeChild(XPathAPI.selectSingleNode(doc.getDocumentElement(), "//xml/node5"));
            doc.getDocumentElement().removeChild(XPathAPI.selectSingleNode(doc.getDocumentElement(), "//xml/node6"));
        }
        //OutputFormat fmt = new OutputFormat();
        //StringWriter sw = new StringWriter();
        //XMLSerializer ser = new XMLSerializer(sw, fmt);
        //ser.serialize(doc);
        //String s2 = sw.toString();
        DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS)reg.getDOMImplementation("LS");
        LSSerializer ser = impl.createLSSerializer();
        ////ser.getDomConfig().setParameter("format-pretty-print", true);
        String s2 = ser.writeToString(doc);
        //
        System.out.println(s2);
    }
}
