标签:
1 | <?xml version=”” encoding=”” standalone=”” ?> |
1 2 3 4 5 6 | <![CDATA[ <html> <head></head> <body></body> </html>]]> |
1 2 3 4 | <?xml version="1.0" encoding="UTF-8"?><!-- 1. 编写要解析的XML文件 --><users></users> |
1 2 3 4 5 6 7 | public static DocumentBuilder getParser()throws Exception{ // 创建工厂类对象 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); // 获取解析器对象 DocumentBuilder parser = factory.newDocumentBuilder(); return parser;} |
1 2 3 4 5 6 7 | public static Document getDOM(File file)throws Exception{ // 获取解析器 DocumentBuilder parser = getParser(); // 解析数据 Document dom = parser.parse(file); return dom;} |
1 2 3 4 5 6 7 8 | public static void getRoot(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 遍历dom树找根元素 Node node = dom.getElementsByTagName("users").item(0); // 输出根元素的名 System.out.println(node.getNodeName());} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static void getRoot(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 遍历dom树找根元素 Node node = dom.getElementsByTagName("users").item(0); // 输出根元素的名 System.out.println(node.getNodeName()); // 根据节点直接的关系获取根元素 NodeList list = dom.getChildNodes(); Node root = list.item(0); System.out.println(root.getNodeName()); root = dom.getFirstChild(); System.out.println(root.getNodeName()); root = dom.getLastChild(); System.out.println(root.getNodeName()); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static Document addElement(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 创建user元素 Element user = dom.createElement("user"); Element name = dom.createElement("name"); Element age = dom.createElement("age"); Element address = dom.createElement("address"); name.setTextContent("焦宁波"); age.setTextContent("28"); address.setTextContent("天河区"); // 建立关系 Element root = (Element) dom.getFirstChild(); user.appendChild(name); user.appendChild(age); user.appendChild(address); root.appendChild(user); // 返回修改后的DOM树对象 return dom;} |
1 2 3 4 5 6 7 8 | public static void writeDOM2XML(Document dom,File file)throws Exception{ // 获取转换器的工厂类对象 TransformerFactory factory = TransformerFactory.newInstance(); // 获取转换器对象 Transformer trans = factory.newTransformer(); // 转换 trans.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(file))); } |
1 2 3 4 5 6 7 8 9 | public static Document modifyElement(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 获取第二个age元素 Node age2 = dom.getElementsByTagName("age").item(1); // 设置文本值 age2.setTextContent("30"); return dom;} |
1 2 3 4 5 6 7 8 9 10 11 | public static Document removeElement(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 获取user的父亲 Node users = dom.getFirstChild(); // 获取需要断绝关系的孩子节点 Node user1 = dom.getElementsByTagName("user").item(0); // 断绝关系 users.removeChild(user1); return dom;} |
1 2 3 4 5 6 7 8 9 | public static Document removeElement(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 获取user的父亲 Node users = dom.getFirstChild(); Node user1 = users.getChildNodes().item(1); users.removeChild(user1); return dom; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public static void searchElement(File file)throws Exception{ // 8.1获取DOM树 Document dom = getDOM(file); // 8.2获取第二个user的所有的子元素并输入元素名 Element user2 = (Element) dom.getElementsByTagName("user").item(1); // 8.3获取所有的儿子 NodeList list = user2.getChildNodes(); // 8.4遍历所有的孩子 for(int i = 0;i<list.getLength();i++){ Node node = list.item(i); System.out.println(node.getNodeName()); } // 8.5获取第二个user的address元素 Element address2 = (Element) list.item(2); System.out.println(address2.getNodeName()); Node age2 = address2.getPreviousSibling(); System.out.println(age2.getNodeName()); Element name2 = (Element) list.item(0); System.out.println(name2.getNodeName()); age2 = name2.getNextSibling(); System.out.println(age2.getNodeName());} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static Document optionAttribute(File file)throws Exception{ // 获取DOM树 Document dom = getDOM(file); // 获取所有的user元素 NodeList list = dom.getElementsByTagName("user"); // 遍历节点 for (int i = 0; i < list.getLength(); i++) { Element user = (Element)list.item(i); // 添加属性 user.setAttribute("id", "00"+(i+1)); } // 获取属性 Element user2 = (Element) list.item(1); String value = user2.getAttribute("id"); System.out.println(value); // 修改属性 user2.setAttribute("id", "007"); // 删除属性 user2.removeAttribute("id"); return dom; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0" encoding="UTF-8" standalone="no"?><linkmans> <linkman> <name>jack</name> <phone>18663243245</phone> <email>jack@163.com</email> </linkman> <linkman> <name>张三</name> <phone>1353243247</phone> <email>zs@126.com</email> </linkman></linkmans> |
1 2 3 4 5 6 | public static SAXParser getParser()throws Exception{ // 获取解析器工厂类对象 SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); return parser;} |
1 2 3 4 5 6 | public static void getElement(File file,DefaultHandler dh) throws Exception{ // 获取解析器 SAXParser parser = getParser(); // 调用解析方法 parser.parse(file, dh);} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class MyHandler extends DefaultHandler { // 当文档开始解析的时候自动执行 public void startDocument() throws SAXException { super.startDocument(); System.out.println("XML文档开始解析..."); } // 遇到一个开始元素自动执行 public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { super.startElement(uri, localName, name, attributes); System.out.println("元素"+name+"开始..."); } // 遇到文本内容自动执行 public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); System.out.println("文本内容"+new String(ch,start,length)); } // 遇到元素结束自动执行 public void endElement(String uri, String localName, String name) throws SAXException { super.endElement(uri, localName, name); System.out.println("元素"+name+"结束..."); } // 文档解析完毕的时候自定执行 public void endDocument() throws SAXException { super.endDocument(); System.out.println("XML文档解析结束..."); }} |
1 2 3 4 5 | public static void main(String[] args)throws Exception { File file = new File("linkmans.xml"); MyHandler handler = new MyHandler(); getElement(file,handler); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class OptionDataHandler extends DefaultHandler { // 定义一个成员变量记录标签的名 private String name = null; // 定义一个统计次数的变量 private int count = 0; // 遇到一个开始元素自动执行 public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { super.startElement(uri, localName, name, attributes); this.name = name; if("name".equals(this.name)){ this.count++; } } // 遇到文本内容自动执行 public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); // 判断是否是name元素 if("name".equals(this.name) && this.count == 2){ System.out.println(new String(ch,start,length)); } }} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Linkman { private String name; private String phone; private String email; public Linkman() { super(); } public Linkman(String name, String phone, String email) { super(); this.name = name; this.phone = phone; this.email = email; } // 省略get和set方法} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | public class ListHandler extends DefaultHandler { // 定义javabean对象 private Linkman linkman = null; // 定义一个集合封装javabean对象 private List<Linkman> list = null; // 定义解析的元素的名字 private String name = null; @Override public void startDocument() throws SAXException { super.startDocument(); // 创建list集合的对象 this.list = new ArrayList<Linkman>(); } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { super.startElement(uri, localName, name, attributes); // 记录解析的元素的名 this.name = name; // 如果是linkman那么创建一个Linkman对象 if("linkman".equals(this.name)){ this.linkman = new Linkman(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); // 如果此时元素名是name获取文本值 if("name".equals(this.name)){ this.linkman.setName(new String(ch,start,length)); } // 如果此时元素名是phone获取文本值 if("phone".equals(this.name)){ this.linkman.setPhone(new String(ch,start,length)); } // 如果此时元素名是email获取文本值 if("email".equals(this.name)){ this.linkman.setEmail(new String(ch,start,length)); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { super.endElement(uri, localName, name); // 释放this.name this.name = null; // 如果此时的元素名是linkman if("linkman".equals(name)){ // 将linkman对象添加到集合 this.list.add(this.linkman); // 清空linkman对象 this.linkman = null; } } // 对外提供一个获取封装好linkman集合的方法 public List<Linkman> getList() { return list; }} |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0" encoding="UTF-8" standalone="no"?><linkmans> <linkman> <name>jack</name> <phone>18663243245</phone> <email>jack@163.com</email> </linkman> <linkman> <name>张三</name> <phone>1353243247</phone> <email>zs@126.com</email> </linkman></linkmans> |
1 2 3 | public static SAXReader getReader(){ return new SAXReader();} |
1 2 3 4 5 6 7 | public static Document getDocument(File file)throws Exception{ // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); return doc;} |
1 2 3 4 5 6 7 8 9 | public static void getRoot(File file)throws Exception{ // 4.1获取解析器 SAXReader reader = getReader(); // 4.2解析文档 Document doc = reader.read(file); // 4.3获取根元素 Element root = doc.getRootElement(); System.out.println(root.getName());} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public static void getElement(File file) throws Exception { // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); // 获取根元素 Element root = doc.getRootElement(); // 获取所有的linkman List list = root.elements("linkman"); Iterator it = list.iterator(); // 循环遍历节点 while (it.hasNext()) { Element ele = (Element) it.next(); System.out.println(ele.getName()); } System.out.println("---------------"); // 简化 for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); System.out.println(element.getName()); } // 获取第二个linkman的名字 Element linkman2 = (Element) list.get(1); String name = linkman2.element("name").getText(); System.out.println(name);} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public static Document addElement(File file)throws Exception{ // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); // 获取根元素 Element root = doc.getRootElement(); // 创建新元素 Element new_linkman = DocumentHelper.createElement("linkman"); Element new_name = DocumentHelper.createElement("name"); Element new_phone = DocumentHelper.createElement("phone"); Element new_email = DocumentHelper.createElement("email"); new_name.setText("焦宁波"); new_phone.setText("186xxxxxxxxx"); new_email.setText("jnb@itcast.cn"); // 建立关系 new_linkman.add(new_name); new_linkman.add(new_phone); new_linkman.add(new_email); root.add(new_linkman); return doc; } |
1 2 3 4 5 6 7 8 | public static void writeDocument2XML(Document doc, File file)throws Exception{ // 创建创建一个转换对象。 可以解决输入的数据时中文的乱码问题 XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8")); // 将doc写入指定文件 writer.write(doc); // 释放资源 writer.close();} |
1 2 3 4 5 6 7 8 9 10 11 12 | public static Document modifyElement(File file) throws Exception { // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); // 获取根元素 Element root = doc.getRootElement(); // 直接获取第二个linkman的name Element name =((Element)root.elements("linkman").get(1)).element("name"); name.setText("李四"); return doc;} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static Document removeAll(File file)throws Exception{ // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); // 获取根元素 Element root = doc.getRootElement(); // 获取所有的linkman List list = root.elements("linkman"); // 循环断绝关系 for(Object temp :list){ // 转型 Element linkman = (Element)temp; // 断绝关系 root.remove(linkman); } return doc;} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static Document optionAttribute(File file)throws Exception{ // 获取解析器 SAXReader reader = getReader(); // 解析文档 Document doc = reader.read(file); // 获取根元素 Element root = doc.getRootElement(); // 获取所有的linkman List list = root.elements("linkman"); // 循环添加属性 int count = 0; for(Object temp :list){ // 转型 Element linkman = (Element)temp; // 添加属性 linkman.add(DocumentHelper.createAttribute(linkman,"id", "00"+(count+1))); count++; } } |
1 2 3 4 5 6 7 8 | Element linkman3 = (Element) list.get(2);String value = linkman3.attribute("id").getText();System.out.println(value);// 修改属性linkman3.attribute("id").setText("007");// 删除属性linkman3.remove(linkman3.attribute("id"));return doc; |
1 2 3 4 5 6 7 8 9 10 11 | public static void findQuestion(File file)throws Exception{ // 10.1获取解析器 SAXReader reader = getReader(); // 10.2解析文档 Document doc = reader.read(file); Element inner_name = doc.getRootElement() // 获取根元素 .element("linkman") // 获取第一个linkman元素 .element("linkman") // 获取第一个linkman中的第一个linkman元素 .element("name"); // 获取上面的name元素 System.out.println(inner_name.getText());} |
1 2 3 4 5 6 7 8 | public static void findAnswer(File file)throws Exception{ // 10.1获取解析器 SAXReader reader = getReader(); // 10.2解析文档 Document doc = reader.read(file); Element name = (Element)doc.selectSingleNode("/linkmans/linkman[1]/linkman/name"); System.out.println(name.getText());} |
1 2 | selectNodes(“xpath”) //查询指定路径的所有的元素selectSingleNode(“xpath”) // 查询指定路径的第一个元素 |
| 路径 | 说明 |
|---|---|
| /AAA | 指定从XML文档的根开始写路径 |
| //BBB | 指定从整个XML中搜索满足的元素名 |
| /AAA/CCC/DDD/* | 指定路径下所有的元素 |
| //* | 指定获取所有的元素 |
| /AAA/BBB[1] | 指定路径下的第一个元素,一定是以1开始的 |
| /AAA/BBB[last()] | 指定路径下的最后一个元素 |
| //@id | 指定要获取的属性元素 |
| //BBB[@id] | 指定带属性的元素 |
| //BBB[@id=‘b1‘] | 指定属性值的元素 |
| //BBB[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5)] | 根据计算获取元素 |
1 2 3 4 | <?xml version="1.0" encoding="UTF-8"?><users> <user name="jack" password="root"/></users> |
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static User login(String name, String password, File file) throws Exception { Document doc = getDoc(file); Node node = doc.selectSingleNode("/users/user[@name=‘" + name + "‘ and @password=‘" + password + "‘]"); User user = null; if (node != null) { String name_value = node.valueOf("@name"); String password_value = node.valueOf("@password"); user = new User(name_value, password_value); } return user;} |
1 2 3 4 5 6 7 8 9 10 11 | public static void registUser(User user,File file)throws Exception{ Document doc = getDoc(file); Element root = doc.getRootElement(); Element new_user = DocumentHelper.createElement("user").addAttribute("name", user.getName()) .addAttribute("password", user.getPassword()); root.add(new_user); // 将document对象持久化到文件 XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8")); writer.write(doc); writer.close();} |
标签:
原文地址:http://www.cnblogs.com/lindongdong/p/4874691.html