Apache Muse - Read and Write XML to a File with XmlUtils
The XmlUtils class has a number of methods for performing file I/O with XML documents. If you want to read the contents of an XML file as part of your resource implementation, make sure the file is on your classpath. You can do this in Axis2 or the Mini SOAP Engine by putting the file under /WEB-INF/classes; OSGi users should put the file inside the bundle that holds their implementation code. Once the file is in place, you can use the following code to create a DOM Document:
import java.io.File;
import java.io.InputStream;
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.apache.muse.util.xml.XmlUtils;
...
//
// The path is relative to /WEB-INF/classes or the OSGi bundle root
//
String relativePath = "my/xml/files/example.xml";
InputStream stream = getEnvironment().getDataResourceStream(relativePath);
Document xmlDoc = XmlUtils.createDocument(filePath);
//
// Here is an alternate way to read files if the path is absolute
//
String absolutePath = "/my/xml/files/example.xml";
File file = new File(absolutePath);
Document xmlDoc = XmlUtils.createDocument(file);
You may also need to write an XML fragment to a file, or simply to the console as part of your logging or debugging. Fortunately, you have a number of options:
Element xml = ...
String xmlString = XmlUtils.toString(xml);
System.out.println("XML fragment is:\n\n" + xmlString);
File file = new File("/my/xml/files/example.xml");
XmlUtils.toFile(xml, file);
Note that both the toString() and toFile() methods are overloaded so that you can control how the XML is formatted. Please review the JavaDoc for more details.