Java tutorial
//package com.java2s; /* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ import java.io.ByteArrayInputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class Main { public static Node prependXMLChildFromString(Node parent, String child) throws ParserConfigurationException, SAXException, IOException { if (parent instanceof Document) parent = ((Document) parent).getDocumentElement(); Document newDoc = getXMLFromString(child); Node newNode = parent.getOwnerDocument().importNode(newDoc.getDocumentElement(), true); return parent.insertBefore(newNode, parent.getFirstChild()); } /** * This function does not support validation via DTD. */ public static Document getXMLFromString(String str) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(str.getBytes())); } }