001package org.apache.archiva.xml; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import org.dom4j.Document; 023import org.dom4j.io.OutputFormat; 024 025import java.io.IOException; 026import java.io.Writer; 027 028/** 029 * XMLWriter - Making writing XML files easier. 030 * 031 * 032 */ 033public class XMLWriter 034{ 035 /** 036 * Write the Document to the provided Writer, leaving the Writer open. 037 * 038 * @param doc the document to write. 039 * @param writer the writer to write to. 040 * @throws XMLException if there was a problem writing the xml to the writer. 041 */ 042 public static void write( Document doc, Writer writer ) 043 throws XMLException 044 { 045 write( doc, writer, false ); 046 } 047 048 /** 049 * Write the Document to the provided Writer, with an option to close the writer upon completion. 050 * 051 * @param doc the document to write. 052 * @param writer the writer to write to. 053 * @param close true to close the writer on completion. 054 * @throws XMLException if there was a problem writing the xml to the writer. 055 */ 056 public static void write( Document doc, Writer writer, boolean close ) 057 throws XMLException 058 { 059 org.dom4j.io.XMLWriter xmlwriter = null; 060 061 try 062 { 063 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); 064 xmlwriter = new org.dom4j.io.XMLWriter( writer, outputFormat ); 065 xmlwriter.write( doc ); 066 xmlwriter.flush(); 067 } 068 catch ( IOException e ) 069 { 070 throw new XMLException( "Unable to write xml contents to writer: " + e.getMessage(), e ); 071 } 072 finally 073 { 074 if ( close && ( xmlwriter != null ) ) 075 { 076 try 077 { 078 xmlwriter.close(); 079 } 080 catch ( IOException e ) 081 { 082 /* quietly ignore */ 083 } 084 } 085 } 086 } 087}