Java操作XML的工具类
1 import java.io.File;2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.io.StringWriter;
7 import java.io.Writer;
8
9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerException;
11 import javax.xml.transform.TransformerFactory;
12 import javax.xml.transform.stream.StreamResult;
13 import javax.xml.transform.stream.StreamSource;
14
15 import org.dom4j.Document;
16 import org.dom4j.DocumentException;
17 import org.dom4j.DocumentHelper;
18 import org.dom4j.ProcessingInstruction;
19 import org.dom4j.io.DocumentSource;
20 import org.dom4j.io.OutputFormat;
21 import org.dom4j.io.SAXReader;
22 import org.dom4j.io.XMLWriter;
23
24 public class XMLUtil {
25 /**
26 * 以编码为UTF-8的方式返回xml
27 * @param doc Document
28 * @return String
29 */
30 public static String toString(Document doc) {
31 return toString(doc, "UTF-8");
32 }
33
34 /**
35 * 以指定编码格式返回xml
36 * @param doc Document
37 * @param encoding String
38 * @return String
39 */
40 public static String toString(Document doc, String encoding) {
41 if (null != doc) {
42 OutputFormat outputFormat = new OutputFormat();
43 outputFormat.setEncoding(encoding);
44 StringWriter stringWriter = new StringWriter();
45 XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
46 try {
47 xmlWriter.write(doc);
48 return stringWriter.toString();
49 } catch (IOException ex) {
50 return "";
51 }
52 } else {
53 return "";
54 }
55 }
56
57 private static String converPath( String path ){
58 if(OSUtil.LIUNX.equals(System.getProperty("os.name"))){
59 path = OSUtil.convert2linuxPath(path) ;
60 System.out.println( "system is Linux , path conver to :" + path );
61 }
62 return path ;
63 }
64
65
66 /**
67 * 创建xml格式的文件
68 * @param doc
69 * @param encoding
70 * @param strFileName
71 * @return
72 */
73 public static boolean saveXMLDocumentToFile(Document doc, String encoding, String strFileName) {
74 boolean flag = false;
75 // 创建路径
76 strFileName = converPath(strFileName);
77 String strDir = FileNameUtil.extractFilePath(strFileName);
78 DirectoryUtil.forceDirectory(strDir);
79
80 if (encoding == null || encoding.length() == 0) {
81 encoding = "UTF-8";
82 }
83 OutputFormat outputFormat = new OutputFormat();
84 outputFormat.setEncoding(encoding);
85 FileOutputStream fos = null;
86 XMLWriter xmlWriter = null;
87 try {
88 // FileWriter fileWriter = new FileWriter(strFileName);
89 // XMLWriter xmlWriter = new XMLWriter(fileWriter, outputFormat);//
90 // 不能解决UTF-8编码问题
91 fos = new FileOutputStream(strFileName);// 可解决UTF-8编码问题
92 xmlWriter = new XMLWriter(fos, outputFormat);
93 xmlWriter.write(doc);
94 flag = true;
95 } catch (IOException e) {
96 flag = false;
97 System.out.println("保存xml文件出错:" + e.getMessage());
98 e.printStackTrace();
99 } finally {
100 try {
101 if (xmlWriter != null) {
102 xmlWriter.flush();
103 }
104 if (fos != null) {
105 fos.flush();
106 }
107 if (xmlWriter != null) {
108 xmlWriter.close();
109 }
110 if (fos != null) {
111 fos.close();
112 }
113 } catch (IOException e) {
114 e.printStackTrace();
115 }
116 }
117 return flag;
118 }
119
120 /**
121 * 创建格式化过的xml格式的文件
122 * @param doc
123 * @param encoding
124 * @param strFileName
125 * @return
126 */
127 public static boolean saveFormatXMLDocumentToFile(Document doc, String encoding,
128 String strFileName) {
129 boolean flag = false;
130
131 // 创建路径
132 strFileName = converPath(strFileName);
133 String strDir = FileNameUtil.extractFilePath(strFileName) ;
134 DirectoryUtil.forceDirectory(strDir);
135
136 if (encoding == null || encoding.length() == 0) {
137 encoding = "UTF-8";
138 }
139 OutputFormat outputFormat = OutputFormat.createPrettyPrint();
140 outputFormat.setEncoding(encoding);
141 FileOutputStream fos = null;
142 XMLWriter xmlWriter = null;
143 try{
144 fos = new FileOutputStream(strFileName);// 可解决UTF-8编码问题
145 xmlWriter = new XMLWriter(fos, outputFormat);
146 xmlWriter.write(doc);
147 flag = true;
148 }catch(IOException e){
149 flag = false;
150 }finally{
151 try {
152 xmlWriter.flush();
153 fos.flush();
154 xmlWriter.close();
155 fos.close();
156 } catch (IOException e) {
157 e.printStackTrace();
158 }
159
160 }
161 return flag;
162 }
163
164 public static void saveXMLDocumentToOutputStream(Document doc,
165 String encoding, OutputStream outputstream) throws IOException {
166 if (encoding == null || encoding.length() == 0) {
167 encoding = "UTF-8";
168 }
169 OutputFormat outputFormat = new OutputFormat();
170 outputFormat.setEncoding(encoding);
171 XMLWriter xmlWriter = new XMLWriter(outputstream, outputFormat);
172 xmlWriter.write(doc);
173 xmlWriter.close();
174 outputstream.close();
175 }
176
177 public static Document loadXMLFile(String strFileName)
178 throws DocumentException {
179 SAXReader saxReader = new SAXReader();
180 saxReader.setValidation(false);
181 saxReader.setEntityResolver(new IgnoreDTDEntityResolver());
182 return saxReader.read(new File(OSUtil.convert2linuxPath(strFileName)));
183 }
184
185 public static Document loadXMLInputstream(InputStream in){
186 SAXReader reader = new SAXReader();
187 try {
188 return reader.read(in);
189 } catch (DocumentException e) {
190 return null;
191 }
192 }
193
194 /**
195 * 用于xml 与 xsl 的归并输出含处理指令的xml到out
196 * 处理指令指定了浏览器渲染的时候使用的xsl文件相对路径
197 *
198 * @author sun
199 */
200 @SuppressWarnings("unchecked")
201 public static void outputXML(Document xmldoc, String xslname,
202 Writer out) throws Exception {
203 if (xslname != null) {
204 ProcessingInstruction pi = DocumentHelper
205 .createProcessingInstruction("xml-stylesheet", "href=\""
206 + xslname + "\" type=\"text/xsl\"");
207 xmldoc.content().add(0, pi);
208 }
209 TransformerFactory factory = TransformerFactory.newInstance();
210 Transformer transformer = factory.newTransformer();
211 transformer.setOutputProperty("encoding", "UTF-8");
212
213 transformer
214 .transform(new DocumentSource(xmldoc), new StreamResult(out));
215 out.flush();
216 out.close();
217 }
218
219 /**
220 * 用于xml 与 xsl 的归并输出xml或html到out
221 * 输出html时,xsl名称不能为null
222 * @author
223 * @throws TransformerException
224 */
225 public static void transformXml(Document xmldoc, String xslname,
226 Writer out) throws TransformerException{
227 TransformerFactory factory = TransformerFactory.newInstance();
228 Transformer transformer = xslname == null ? factory.newTransformer()
229 : factory.newTransformer(new StreamSource(xslname));
230 transformer.setOutputProperty("encoding", "UTF-8");
231
232 transformer.transform(new DocumentSource(xmldoc),
233 new StreamResult(out));
234 }
235 }
以上是 Java操作XML的工具类 的全部内容, 来源链接: utcz.com/z/392125.html