代码都是来自于网上,稍微做了一下修改。
dom方式;
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; 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.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DomDemo { private Document document; private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); private static DocumentBuilder builder = null; public DomDemo() { init(); } private void init() { try { builder = dbf.newDocumentBuilder(); this.document = builder.newDocument(); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } } public void createXml(String fileName) { Element root = this.document.createElement("employees"); this.document.appendChild(root); Element employee = this.document.createElement("employee"); Element name = this.document.createElement("name"); name.appendChild(this.document.createTextNode("DomDemo")); employee.appendChild(name); Element sex = this.document.createElement("sex"); sex.appendChild(this.document.createTextNode("m")); employee.appendChild(sex); Element age = this.document.createElement("age"); age.appendChild(this.document.createTextNode("30")); employee.appendChild(age); root.appendChild(employee); TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); System.out.println("生成XML文件成功!"); } catch (TransformerConfigurationException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (TransformerException e) { System.out.println(e.getMessage()); } } public void parserXml(String fileName) { try { Document document = builder.parse(fileName); NodeList employees = document.getChildNodes(); for (int i = 0; i < employees.getLength(); i++) { Node employee = employees.item(i); NodeList employeeInfo = employee.getChildNodes(); for (int j = 0; j < employeeInfo.getLength(); j++) { Node node = employeeInfo.item(j); NodeList employeeMeta = node.getChildNodes(); for (int k = 0; k < employeeMeta.getLength(); k++) { System.out.println(employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent()); } } } System.out.println("解析完毕"); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { DomDemo dom = new DomDemo(); String fileName = "d:/DomDemo.xml"; dom.createXml(fileName); dom.parserXml(fileName); } }
import java.io.File; import java.util.Vector; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class SAXDemo extends DefaultHandler { private Vector<String> tagName; private Vector<String> tagValue; private int step; // 开始解析XML文件 public void startDocument() throws SAXException { tagName = new Vector<String>(); tagValue = new Vector<String>(); step = 0; } // 结束解析XML文件 public void endDocument() throws SAXException { for (int i = 0; i < tagName.size(); i++) { if (!tagName.get(i).equals("") || tagName.get(i) != null) { System.out.println("节点名称:" + tagName.get(i)); System.out.println("节点值:" + tagValue.get(i)); } } } /** * 在解释到一个开始元素时会调用此方法.但是当元素有重复时可以自己写算法来区分 这些重复的元素.qName是什么? <name:page * ll=""></name:page>这样写就会抛出SAXException错误 通常情况下qName等于localName */ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // 节点名称 tagName.add(qName); // 循环输出属性 for (int i = 0; i < attributes.getLength(); i++) { // 获取属性名称 System.out.println("属性名称:" + attributes.getQName(i)); // 获取属性值 System.out.println("属性值:" + attributes.getValue(attributes.getQName(i))); } } /** * 在遇到结束标签时调用此方法 */ public void endElement(String uri, String localName, String qName) throws SAXException { step = step + 1; } /** * 读取标签里的值,ch用来存放某行的xml的字符数据,包括标签,初始大小是2048, 每解释到新的字符会把它添加到char[]里。 * * 注意,这个char字符会自己管理存储的字符, 并不是每一行就会刷新一次char,start,length是由xml的元素数据确定的, * 暂时找不到规律,以后看源代码. * * 这里一个正标签,反标签都会被执行一次characters,所以在反标签时不用获得其中的值 */ public void characters(char ch[], int start, int length) throws SAXException { // 只要当前的标签组的长度一至,值就不赋,则反标签不被计划在内 if (tagName.size() - 1 == tagValue.size()) { tagValue.add(new String(ch, start, length)); } } public static void main(String[] args) { String filename = "d:/SAXDemo.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser saxParser = spf.newSAXParser(); saxParser.parse(new File(filename), new SAXDemo()); } catch (Exception e) { e.printStackTrace(); } } }
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jDemo { public void createXml(String fileName) { Document document = DocumentHelper.createDocument(); Element employees = document.addElement("employees"); Element employee = employees.addElement("employee"); Element name = employee.addElement("name"); name.setText("Dom4jDemo"); Element sex = employee.addElement("sex"); sex.setText("m"); Element age = employee.addElement("age"); age.setText("29"); try { Writer fileWriter = new FileWriter(fileName); XMLWriter xmlWriter = new XMLWriter(fileWriter); xmlWriter.write(document); xmlWriter.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } public void parserXml(String fileName) { File inputXml = new File(fileName); SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(inputXml); Element employees = document.getRootElement(); for (Iterator<?> i = employees.elementIterator(); i.hasNext();) { Element employee = (Element) i.next(); for (Iterator<?> j = employee.elementIterator(); j.hasNext();) { Element node = (Element) j.next(); System.out.println(node.getName() + ":" + node.getText()); } } } catch (DocumentException e) { System.out.println(e.getMessage()); } System.out.println("dom4j parserXml"); } public static void main(String[] args) { Dom4jDemo dom4j = new Dom4jDemo(); String fileName = "d:/Dom4jDemo.xml"; dom4j.createXml(fileName); dom4j.parserXml(fileName); } }
import java.io.FileOutputStream; import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.jdom.xpath.XPath; public class JDomDemo { public void createXml(String fileName) { Document doc = new Document(); Element employees = new Element("employees"); doc.setRootElement(employees); Element employee = new Element("employee"); Element name = new Element("name"); name.setText("JDomDemo"); employees.addContent(employee); employee.addContent(name); name.setAttribute("attr", "a"); XMLOutputter xmlOut = new XMLOutputter(); Format fmt = Format.getPrettyFormat(); fmt.setIndent(" ");// 四个空格 fmt.setEncoding("gb2312"); xmlOut.setFormat(fmt); FileOutputStream out = null; try { out = new FileOutputStream(fileName); xmlOut.output(doc, out); } catch (IOException e) { e.printStackTrace(); } } public void parserXml(String fileName) { SAXBuilder sax = new SAXBuilder(); try { Document doc = sax.build(fileName); Element rootEle = doc.getRootElement(); Element nameElement = (Element) XPath.selectSingleNode(rootEle, "/employees/employee/name"); String name = nameElement.getText(); System.out.println("name = " + name); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { JDomDemo jDomDemo = new JDomDemo(); String fileName = "d:/JDomDemo.xml"; jDomDemo.createXml(fileName); jDomDemo.parserXml(fileName); } }