java 中怎么利用org.w3c.dom操作XML文件,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
下面直接贴出样例代码:
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;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.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Date;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Scanner;import java.util.Set;public class XMLSample{private static void writeXML(Document document, String filePath) { TransformerFactory transFactory = TransformerFactory.newInstance();Transformer transformer = null;try {String parent = new File(filePath).getParent();File pDir = new File(parent);if (!pDir.exists()) {pDir.mkdirs();}OutputStream os = new FileOutputStream(new File(filePath));transformer = transFactory.newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");DOMSource source = new DOMSource();source.setNode(document);StreamResult result = new StreamResult();result.setOutputStream(os);transformer.transform(source, result);os.flush();} catch (TransformerConfigurationException e) {e.printStackTrace();} catch (TransformerException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} private static Document readXML(String file) { try { // 得到DOM解析器的工厂实例DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // 从DOM工厂中获得DOM解析器DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder(); // 把要解析的xml文档读入DOM解析器Document doc = dbBuilder.parse(file);return doc;} catch (Exception e) {e.printStackTrace();}return null;} public static void showXMLDetail() { Document document = readXML(mapperFilePath); // 获取标签名为"dataset"的元素Node mapper = document.getElementsByTagName("dataset").item(0); // 下面依次读取dataset元素的每个子元素,每个子元素的标签名字为nodefor (int i = 0; i < mapper.getChildNodes().getLength(); i++) {Node node = mapper.getChildNodes().item(i);String s = item.getNodeName();if(s.toLowerCase().equals("#comment")){System.out.println("这是注释内容: "+node.getTextContent());}else if(s.toLowerCase().equals("#text")){System.out.println("呐,这是标签之外的文本: "+node.getTextContent());}else if ("node".equals(s)) {// 获取元素属性的值String column = item.getAttributes().getNamedItem("column").getNodeValue();String field = item.getAttributes().getNamedItem("property").getNodeValue();}else{// 其他的就不要了} } } public static void generateXML(){try {Element root;Set<String> set = new HashSet<>();set.add("node");DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setNamespaceAware(true);DocumentBuilder documentBuilder = null;documentBuilder = factory.newDocumentBuilder();Document document = documentBuilder.newDocument();root = document.createElement("dataset");document.appendChild(root);set.forEach(p -> {Element element = document.createElement(p);element.setAttribte("column","haha");element.setAttribte("property","heihei");root.appendChild(element);});writeXML(document, "d:/allTables.xml");} catch (ParserConfigurationException e) {e.printStackTrace();}}}
Java操作XML(使用org.w3c.dom)
一、创建DOM
XMLBuilder.java 用于创建DOM,Root结点 package rochoc.xml.oper; import java.io.File;import java.io.IOException; import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.xml.sax.SAXException; public class XmlBuilder{ public XmlBuilder(String path) { this.path=path; init(); } public void init() { buildDocument(); buildRoot(); } private void buildDocument() { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); logger.debug("Construct document builder success."); doc=builder.parse(new File(path)); logger.debug("Build xml document success."); }catch(ParserConfigurationException e) { logger.error("Construct document builder error:"+e); }catch(SAXException e) { logger.error("Parse xml file error:"+e); }catch(IOException e) { logger.error("Read xml file error:"+e); } } private void buildRoot() { root=doc.getDocumentElement(); } public Document getDoc() { return doc; } public void setDoc(Document doc) { this.doc = doc; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Element getRoot() { return root; } public void setRoot(Element root) { this.root = root; } private String path=null;//xml文件路径 private Document doc=null;//xml文件对应的document private Element root=null;//xml文件的根结点 private Logger logger=Logger.getLogger(getClass().getName());}
二、查找,插入,删除,修改
XmlOper.java 用于操作XML文件,包括查找、新增、删除、修改结点 package rochoc.xml.oper; import java.util.ArrayList; import org.apache.log4j.Logger;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList; public class XmlOper{ private XmlOper() { } public static NodeList getNodeList(Element parent) { return parent.getChildNodes(); } public static Element [] getElementsByName(Element parent,String name) { ArrayList resList=new ArrayList(); NodeList nl=getNodeList(parent); for(int i=0;i<nl.getLength();i++) { Node nd=nl.item(i); if(nd.getNodeName().equals(name)) { resList.add(nd); } } Element [] res=new Element [resList.size()]; for(int i=0;i<resList.size();i++) { res[0]=(Element)resList.get(i); } logger.debug(parent.getNodeName()+"'s children of "+name+ "'s num:"+res.length); return res; } public static String getElementName(Element element) { return element.getNodeName(); } public static String getElementValue(Element element) { NodeList nl=element.getChildNodes(); for(int i=0;i<nl.getLength();i++) { if(nl.item(i).getNodeType()==Node.TEXT_NODE)//是一个Text Node { logger.debug(element.getNodeName()+" has a Text Node."); return element.getFirstChild().getNodeValue(); } } logger.error(element.getNodeName()+" hasn't a Text Node."); return null; } public static String getElementAttr(Element element,String attr) { return element.getAttribute(attr); } public static void setElementValue(Element element,String val) { Node node=element.getOwnerDocument().createTextNode(val); NodeList nl=element.getChildNodes(); for(int i=0;i<nl.getLength();i++) { Node nd=nl.item(i); if(nd.getNodeType()==Node.TEXT_NODE)//是一个Text Node { nd.setNodeValue(val); logger.debug("modify "+element.getNodeName()+"'s node value succe."); return; } } logger.debug("new "+element.getNodeName()+"'s node value succe."); element.appendChild(node); } public static void setElementAttr(Element element, String attr,String attrVal) { element.setAttribute(attr,attrVal); } public static void addElement(Element parent,Element child) { parent.appendChild(child); } public static void addElement(Element parent,String tagName) { Document doc=parent.getOwnerDocument(); Element child=doc.createElement(tagName); parent.appendChild(child); } public static void addElement(Element parent,String tagName,String text) { Document doc=parent.getOwnerDocument(); Element child=doc.createElement(tagName); setElementValue(child,text); parent.appendChild(child); } public static void removeElement(Element parent,String tagName) { logger.debug("remove "+parent.getNodeName()+"'s children by tagName "+tagName+" begin..."); NodeList nl=parent.getChildNodes(); for(int i=0;i<nl.getLength();i++) { Node nd=nl.item(i); if(nd.getNodeName().equals(tagName)) { parent.removeChild(nd); logger.debug("remove child '"+nd+"' success."); } } logger.debug("remove "+parent.getNodeName()+"'s children by tagName "+tagName+" end."); } static Logger logger=Logger.getLogger("XmlOper");}
三、新建XML文件
XmlCreater.java 用于创建XML文件 package rochoc.xml.oper; import java.io.File; 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.apache.log4j.Logger;import org.w3c.dom.Document;import org.w3c.dom.Element; public class XmlCreater{ public XmlCreater(String path) { this.path=path; init(); } private void init() { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); doc=builder.newDocument();//新建DOM }catch(ParserConfigurationException e) { logger.error("Parse DOM builder error:"+e); } } public Element createRootElement(String rootTagName) { if(doc.getDocumentElement()==null) { logger.debug("create root element '"+rootTagName+"' success."); Element root=doc.createElement(rootTagName); doc.appendChild(root); return root; } logger.warn("this dom's root element is exist,create fail."); return doc.getDocumentElement(); } public Element createElement(Element parent,String tagName) { Document doc=parent.getOwnerDocument(); Element child=doc.createElement(tagName); parent.appendChild(child); return child; } public Element createElement(Element parent,String tagName,String value) { Document doc=parent.getOwnerDocument(); Element child=doc.createElement(tagName); XmlOper.setElementValue(child,value); parent.appendChild(child); return child; } public void createAttribute(Element parent,String attrName,String attrValue) { XmlOper.setElementAttr(parent,attrName,attrValue); } public void buildXmlFile() { TransformerFactory tfactory=TransformerFactory.newInstance(); try { Transformer transformer=tfactory.newTransformer(); DOMSource source=new DOMSource(doc); logger.debug("New DOMSource success."); StreamResult result=new StreamResult(new File(path)); logger.debug("New StreamResult success."); transformer.setOutputProperty("encoding","GBK"); transformer.transform(source,result); logger.debug("Build XML File '"+path+"' success."); }catch(TransformerConfigurationException e) { logger.error("Create Transformer error:"+e); }catch(TransformerException e) { logger.error("Transformer XML file error:"+e); } } public Document getDoc() { return doc; } public void setDoc(Document doc) { this.doc = doc; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } private Logger logger = Logger.getLogger(getClass().getName()); private Document doc=null;//新创建的DOM private String path=null;//生成的XML文件绝对路径}
关于java 中怎么利用org.w3c.dom操作XML文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。