、
1、首先在项目路径下引入dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar包,jaxp方式解析xml文件
<?xml version="1.0" encoding="UTF-8"?> <students> <student name="cn.itcast_0001"> <name>dogdogdog</name> <age>21</age> <sex>男</sex> </student> </students>
package cn.itcast_020; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; //解析xml文件 jaxp解析方式 public class Demo1 { // 获得所有学生的信息 public static void main(String[] args) { // 1 获得jaxp工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 2通过工厂获得解析器实现类 try { DocumentBuilder builder = factory.newDocumentBuilder(); // 3使用解析器加载xml文档==>document Document doc = builder.parse(new File("src/student.xml")); // 4获得所有学生元素的集合 NodeList studentList = doc.getElementsByTagName("student"); // 5遍历集合 for (int i = 0; i < studentList.getLength(); i++) { Element stuEle = (Element) studentList.item(i); // 获得学生元素的number属性 String number = stuEle.getAttribute("number"); // 获得学生节点下的所有子节点(包括文本在内的一共7个) NodeList children = stuEle.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node node = children.item(j); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if (child.getNodeName().equals("name")) { String name = child.getTextContent(); System.out.println(name); } else if (child.getNodeName().equals("age")) { String age = child.getTextContent(); System.out.println(age); } else if (child.getNodeName().equals("sex")) { String sex = child.getTextContent(); System.out.println(sex); } } } } } catch (Exception e) { } } }
2、自己背着敲的代码
package cn.itcast_020; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; //解析xml文件 jaxp解析方式 public class Demo2 { public static void main(String[] args) { // 创建jaxp解析工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 获得jaxp解析器 try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/student.xml"); NodeList nodelist = document.getElementsByTagName("student"); for (int i = 0; i < nodelist.getLength(); i++) { Element element = (Element) nodelist.item(i); String number = element.getAttribute("number"); NodeList nodes = element.getChildNodes(); for (int j = 0; j < nodes.getLength(); j++) { Node node = nodes.item(j); if (node.getNodeType() == Node.ELEMENT_NODE) {// 由于得到的数组中有可能有空字符串,所以要判断是不是Element Element child = (Element) node; if (child.getNodeName().equals("name")) { String name = child.getTextContent(); System.out.println(name); } else if (child.getNodeName().equals("sex")) { String sex = child.getTextContent(); System.out.println(sex); } else { String age = child.getTextContent(); System.out.println(age); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3、使用dom4j进行解析,一个读,一个写 (addElement)
package cn.itcast_020; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter; import org.dom4j.io.XMLWriter; public class Dom4jAddElement { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document doc = reader.read(new File("src/student.xml")); // 1获得根元素 Element rootElement = doc.getRootElement(); // 2添加Element,添加number属性 Element ele = rootElement.addElement("student").addAttribute( "number", "cn.itcast_0011"); // 3添加name age sex子元素并添加子元素中的文本 ele.addElement("name").addText("狗"); ele.addElement("age").addText("16"); ele.addElement("sex").addText("男"); // 4将document对象写到文件中 // 创建格式化器 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); try { // 创建写入器 // 使用字节流绝对不会出现乱码 XMLWriter xml = new XMLWriter(new FileOutputStream( "src/student2.xml"), format); // 写入 xml.write(doc); // 关闭资源 xml.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4、dom4j ,RemoveElement
package cn.itcast_020; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jRemoveElementWithXPath { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document doc = reader.read(new File("src/student2.xml")); //获得根元素 Element root = doc.getRootElement(); //使用xpath找到我们需要的元素 //定义xpath String XPath = "//student[@number='cn.itcast_0011']"; Element node = (Element) root.selectSingleNode(XPath); //删除 System.out.println(node.getParent().remove(node)); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileOutputStream( "src/student3.xml"), format); writer.write(doc); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5、Dom4jXPath修改学生
package cn.itcast_020; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jXPath修改学生 { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document doc = reader.read(new File("src/student2.xml")); Element ele = doc.getRootElement(); String xpath = "//student[@number='cn.itcast_0011']"; Element student = (Element) ele.selectSingleNode(xpath); student.element("age").setText("22"); student.element("sex").setText("男"); student.element("name").setText("赵维真"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileOutputStream( "src/student4.xml"), format); writer.write(doc); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
6、dom解析与sax解析的区别
package cn.itcast_020; import java.io.File; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; //dom4j解析适用于含有根元素的Xml文档 //而sax解析和dom解析适用于各种文档 //sax解析占用的内存比较少,效率高,但是不可以增删改查 //dom解析占用的内存多,但是可以增删改查 public class Dom4j解析 { public static void main(String[] args) { SAXReader reader = new SAXReader(); Document doc; try { doc = reader.read(new File("src/student.xml")); //1获得根元素 Element root = doc.getRootElement(); //2迭代根元素下的所有名叫student的子元素 for (Iterator it = root.elementIterator(); it.hasNext();) { Element ele = (Element) it.next(); //3获得student元素的number属性 String number = ele.attributeValue("name"); System.out.println("number" + number); //4获得stuent子元素的内容(name age sex) String name = ele.elementText("name"); System.out.println("name" + name); String age = ele.elementText("age"); System.out.println("age" + age); String sex = ele.elementText("sex"); System.out.println("sex" + sex); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
7、sax解析
package cn.itcast_020; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyHandler extends DefaultHandler { @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); System.out.println("文档开始解析啦"); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); System.out.println("文档解析完毕"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // 该方法主要获得元素的名称和属性 super.startElement(uri, localName, qName, attributes); if (qName.equals("student")) { String name = attributes.getValue("number"); System.out.println("number" + name); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { // 主要解析文档的中node中节点中的内容 super.characters(ch, start, length); String content = new String(ch, start, length); System.out.println(content); } }
8、sax解析
package cn.itcast_020; import java.io.File; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; public class SAX解析 { public static void main(String[] args) { // 1 创建sax解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); // 2获取sax解析器 try { SAXParser parser = factory.newSAXParser(); // 3解析文档 parser.parse(new File("src/student.xml"), new MyHandler()); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
9、sax解析形成的dao
package cn.itcast_020; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class StudentXMLDao { private StudentXMLDao() { } public StudentXMLDao newInstance() { return new StudentXMLDao(); } public boolean Add(Student stu) { SAXReader reader = new SAXReader(); try { Document doc = reader.read(new File(this.getClass() .getClassLoader().getResource("student.xml").getPath())); // 1获得根元素 Element rootElement = doc.getRootElement(); // 2添加Element,添加number属性 Element ele = rootElement.addElement("student"); // 3添加name age sex子元素并添加子元素中的文本 ele.addElement("name").addText(stu.getName()); ele.addElement("age").addText(String.valueOf(stu.getAge())); ele.addElement("sex").addText(stu.getSex()); // 4将document对象写到文件中 // 创建格式化器 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); try { // 创建写入器 // 使用字节流绝对不会出现乱码 XMLWriter xml = new XMLWriter(new FileOutputStream( "src/student2.xml"), format); // 写入 xml.write(doc); // 关闭资源 xml.close(); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } }