xml解析
package XMLParse; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * dom4j解析xml 对内存消耗小,可进行crud操作 * * @author l */ public class Dom4jParseXml { private static final String path = "src/student.xml"; private static final String newPath = "src/books.xml"; private static final String book = "src/book.xml"; public static void readXml() { } public static void writeToXml(Document document) throws Exception { FileOutputStream fileOutputStream = new FileOutputStream(book); OutputStreamWriter outputStreamWriter = new OutputStreamWriter( fileOutputStream, "utf-8"); XMLWriter writer = new XMLWriter(outputStreamWriter); writer.write(document); writer.close(); } public static void update(Document document) throws Exception { String pattern = "//book[@id='b3']/title"; Node node = document.selectSingleNode(pattern); System.out.println(node.getText()); node.setText("java疯狂讲义"); System.out.println(node.getText()); // FileOutputStream fileOutputStream = new FileOutputStream(book); // OutputStreamWriter outputStreamWriter = new OutputStreamWriter( // fileOutputStream, "utf-8"); // XMLWriter writer = new XMLWriter(outputStreamWriter); // writer.write(document); // writer.close(); } public static void delete(Document document) throws Exception { Element root = document.getRootElement(); for (Iterator<?> it = root.elementIterator(); it.hasNext();) { Element book = (Element) it.next(); String id = book.attributeValue("id"); if ("1".equals(id)) { Element parent = book.getParent(); parent.remove(book); } } // Node node = (Element) document.selectSingleNode("//book[@id='b3']"); // System.out.println(node); // Element parent = node.getParent(); // System.out.println(parent); // parent.remove(node); // System.out.println(parent); } public static void main(String[] args) throws Exception { // 获取解析器 SAXReader saxReader = new SAXReader(); // 指定解析那个文件 Document document = saxReader.read(book); // 可以使用xpath随心所欲读取 // List element = document.selectNodes("/class/student/name"); // // System.out.println(((Attribute) element.get(0)).getText()); // for (int i = 0; i < element.size(); i++) { // System.out.println(((Element) element.get(i)).getText()); // } // //delete(document); update(document); // FileOutputStream fileOutputStream = new FileOutputStream(book); // OutputStreamWriter outputStreamWriter = new OutputStreamWriter( // fileOutputStream, "utf-8"); // XMLWriter writer = new XMLWriter(outputStreamWriter); // writer.write(document); // writer.close(); writeToXml(document); } }
package XMLParse; import java.io.File; import java.io.IOException; 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.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * desc:通过dom技术解析xml文件,实现crud操作 * * @author lc */ public class DomParseXml { private static final String path = "src/student.xml"; public static void read(Document document) throws TransformerConfigurationException { NodeList nodeList = document.getElementsByTagName("student"); Element element = (Element) nodeList.item(0); System.out.println("该学生的年龄是:" + element.getAttribute("age")); Element name = (Element) element.getElementsByTagName("age").item(0); System.out.println(name.getTextContent()); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); try { t.transform(new DOMSource(document), new StreamResult(path)); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readXml(Document document) { NodeList nodeList = document.getElementsByTagName("student"); System.out.println(nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Element stu = (Element) nodeList.item(i); // String name = stu.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); // System.out.println(name); // String age = stu.getElementsByTagName("age").item(0).getFirstChild().getNodeValue(); // System.out.println(age); // String introduce = stu.getElementsByTagName("introduce").item(0).getFirstChild().getNodeValue(); // System.out.println(introduce); Element name = (Element)stu.getElementsByTagName("name").item(0); System.out.println(name.getTextContent()); Element age = (Element)stu.getElementsByTagName("age").item(0); System.out.println(age.getTextContent()); Element introduce = (Element)stu.getElementsByTagName("introduce").item(0); System.out.println(introduce.getTextContent()); } } public static void addXml(Document document) throws Exception { Element stu = document.createElement("student"); Element stu_name = document.createElement("name"); stu_name.setTextContent("小六"); Element stu_age = document.createElement("age"); stu_age.setTextContent("22"); Element stu_introduce = document.createElement("introduce"); stu_introduce.setTextContent("生存或是死亡,这是一个问题"); stu.appendChild(stu_name); stu.appendChild(stu_age); stu.appendChild(stu_introduce); document.getDocumentElement().appendChild(stu); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // t.transform(new DOMSource(document), new StreamResult(path)); } public static void deleteXml(Document document) throws Exception { Node node = document.getElementsByTagName("student").item(2); System.out.println(node.getParentNode().getNodeName()); node.getParentNode().removeChild(node); // 更新xml // 获取转换工厂 // TransformerFactory factory = TransformerFactory.newInstance(); // 获取转换器 // Transformer transformer = factory.newTransformer(); // transformer.transform(new DOMSource(document), new // StreamResult(path)); } public static void updateXml(Document document) { Element node = (Element) document.getElementsByTagName("student").item( 0); Element node_name = (Element) node.getElementsByTagName("name").item(0); node_name.setTextContent("宋江"); } public static void main(String[] args) throws Exception { File xml = new File(path); DocumentBuilderFactory builderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(xml); document.getDocumentElement().normalize(); // System.out.println("根元素:" + // document.getDocumentElement().getNodeName()); NodeList nodelist = document.getElementsByTagName("student"); // 取出第一个学生 // Element stu = (Element) nodelist.item(0); // Element name = (Element) stu.getElementsByTagName("name").item(0); // System.out.println(name.getTextContent()); System.out.println("------------------"); readXml(document); // addXml(document); // deleteXml(document); // updateXml(document); // 更新xml // 获取转换工厂 TransformerFactory factory = TransformerFactory.newInstance(); // 获取转换器 Transformer transformer = factory.newTransformer(); transformer.transform(new DOMSource(document), new StreamResult(path)); } }
package XMLParse; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyDefaultHandler extends DefaultHandler { private boolean isName = false; private boolean isAge = false; @Override public void characters(char[] ch, int start, int length) throws SAXException { String content = new String(ch,start,length); if(!content.equals("") && (isName || isAge)){ System.out.println(content); } isName = false; isAge = false; super.characters(ch, start, length); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); } @Override public void endElement(String uri, String localName, String name) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, name); } @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if(name.equals("name")){ this.isName = true; }else if(name.equals("age")){ this.isAge = true; } } }
package XMLParse; import java.io.File; import java.io.IOException; import java.lang.instrument.ClassDefinition; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; /** * desc: dom解析xml文件会加载到内存,如果xml过大,会导致内存溢出 sax解析可以在不加载全部xml文件时,就可以解析xml文档 * sax只能对xml进行读取,不可进行修改,添加,删除 * * @author lc */ public class SaxParseXml { private static final String path = "src/student.xml"; //private static final String path = "src/status.xml"; public static void main(String[] args) throws Exception, IOException { // 创建代理对象 SAXParserFactory factory = SAXParserFactory.newInstance(); // 创建解析器 SAXParser saxParser = factory.newSAXParser(); // 将xml与事件处理相关联 saxParser.parse(path, new MyDefaultHandler()); } }
package entity; public class Book { public String id; public String title; public String price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", price=" + price + "]"; } }
<?xml version="1.0" encoding="UTF-8" ?> <AAA> <BBB id = "b1"> <CCC> <KKK>k2</KKK> </CCC> <CCC> <KKK>k1</KKK> </CCC> </BBB> <BBB id ="b2"> <BBB name="bbb"></BBB> </BBB> </AAA>
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="2"> <title>java</title> <price>23</price> </book> <book id="b3"> <title>java疯狂讲义</title> <price>34</price> </book> </books>
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <class> <student id="1"> <name>宋江</name> <age>22</age> <introduce>学习Xml-Dom</introduce> </student> <student id ="2"> <name>李四</name> <age>22</age> <introduce>学习Xml-Sax</introduce> </student> <student id ="3"> <name>小六</name> <age>22</age> <introduce>身存或是死亡,这是一个问题</introduce> </student> </class>
DES加密解密
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; public class TestDES { Key key; public TestDES(String str) { getKey(str);//生成密匙 } /** * 根据参数生成KEY */ public void getKey(String strKey) { try { KeyGenerator _generator = KeyGenerator.getInstance("DES"); _generator.init(new SecureRandom(strKey.getBytes())); this.key = _generator.generateKey(); _generator = null; } catch (Exception e) { throw new RuntimeException("Error initializing SqlMap class. Cause: " + e); } } /** * 文件file进行加密并保存目标文件destFile中 * * @param file 要加密的文件 如c:/test/srcFile.txt * @param destFile 加密后存放的文件名 如c:/加密后文件.txt */ public void encrypt(String file, String destFile) throws Exception { Cipher cipher = Cipher.getInstance("DES"); // cipher.init(Cipher.ENCRYPT_MODE, getKey()); cipher.init(Cipher.ENCRYPT_MODE, this.key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); CipherInputStream cis = new CipherInputStream(is, cipher); byte[] buffer = new byte[1024]; int r; while ((r = cis.read(buffer)) > 0) { out.write(buffer, 0, r); } cis.close(); is.close(); out.close(); } /** * 文件采用DES算法解密文件 * * @param file 已加密的文件 如c:/加密后文件.txt * * @param destFile * 解密后存放的文件名 如c:/ test/解密后文件.txt */ public void decrypt(String file, String dest) throws Exception { Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, this.key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024]; int r; while ((r = is.read(buffer)) >= 0) { System.out.println(); cos.write(buffer, 0, r); } cos.close(); out.close(); is.close(); } public static void main(String[] args) throws Exception { TestDES td = new TestDES("aaa"); td.encrypt("d:/status.xml", "d:/jiastatus.xml"); //加密 td.decrypt("d:/jiastatus.xml", "d:/jiestatus.xml"); //解密 System.out.println("执行完成"); } }