package com.itheima;
import java.io.IOException;
import java.lang.reflect.Method;
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.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* */
public class DOM4XMLUtils {
// 获取整个XML文件的Document
public static Document getDocument(String path) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = null;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(path);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return document;
}
// 更新修改后的XML文件
public static void writer2xml(Document document, String path) {
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult(path));
} catch (TransformerConfigurationException e) {
throw new RuntimeException(e);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
// 将xml文件映射成javaBean 注意 xml文件Node 不能为中文
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object converToBean(Class clazz, Node ele) {
Object object = null;
try {
object = clazz.newInstance();
Class[] parameterTypes = new Class[] { String.class };
NodeList list = ele.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
try {
Node node = list.item(i);
String nodeName = node.getNodeName().trim();
String nodeVal = null;
Node valueNode = node.getFirstChild();
if (valueNode != null) {
nodeVal = valueNode.getNodeValue();
}
Object[] arguments = new Object[] { nodeVal };
if (nodeName.length() > 0) {
String first = nodeName.substring(0, 1);
String last = nodeName.substring(1);
Method method = clazz.getMethod(
"set" + first.toUpperCase() + last,
parameterTypes);
method.invoke(object, arguments);
}
} catch (NoSuchMethodException e) {
}
}
return object;
} catch (Exception e) {
return null;
}
}
}
DOM方式读取XML工具类
最新推荐文章于 2022-11-28 09:17:49 发布