使用工厂模式或dom4j 获取document(保存和读取xml文件)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
//工厂模式获取document
public class GetFactory {
public static Document getDocument(String path) throws Exception{
DocumentBuilderFactory documentBuilder=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=documentBuilder.newDocumentBuilder();
Document document=builder.parse(path);
return document;
}
public static void saveXML(Document document,String path){
try {
TransformerFactory factory=TransformerFactory.newInstance();
Transformer former=factory.newTransformer();
former.setOutputProperty(“encoding”, “GBK”);
DOMSource source=new DOMSource(document);
StreamResult result=new StreamResult(new FileOutputStream(path));
former.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
使用dom4j 获取document
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
- 工具类
- @author Administrator
*/
public class Dom4jXML {
public static Document getDocument(String path) throws Exception {
SAXReader read = new SAXReader();
Document document = read.read(path);
return document;
}
public static void saveXML(Document document, String path) throws Exception {
FileOutputStream fos = new FileOutputStream(path);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.close();
fos.close();
}
}
本文地址:https://blog.csdn.net/m0_47460678/article/details/107880921
上一篇: Unity Mask 遮罩无效 解决方案