java基础笔记(6)
xml文件的写入
通过dom生成xml文件:
package com.writexml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.*; import org.w3c.dom.Document; import org.w3c.dom.Element; public class domWrite { public DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); return db; } public void creatXML() throws ParserConfigurationException, TransformerException { DocumentBuilder db = getDocumentBuilder(); Document document = db.newDocument(); document.setXmlStandalone(true);//默认的话会在生成的xml文件声明中将Standalone=“no”,这样会生成说明格式的文档,若要将其不生成,这通过这个语句设置成yes,即true Element bookstore = document.createElement("bookstore");//创建节点 Element book = document.createElement("book"); Element name = document.createElement("name"); name.setTextContent("童话故事"); book.setAttribute("id", "1"); document.appendChild(bookstore);//将bookstore根节点增加到dom树中 bookstore.appendChild(book);//将book节点增加到bookstore根节点中 book.appendChild(name); TransformerFactory tff = TransformerFactory.newInstance();//创建TransformerFactory对象 Transformer tf = tff.newTransformer();//创建Transformer对象 tf.setOutputProperty(OutputKeys.INDENT, "yes");//是否换行 tf.transform(new DOMSource(document), new StreamResult(new File("books01.xml")));//将document输入到文件中 } public static void main(String[] args) throws ParserConfigurationException, TransformerException { // TODO Auto-generated method stub domWrite test = new domWrite(); test.creatXML(); } }
通过SAX生成xml文件:
package com.writexml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.jdom2.Attribute; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import com.entry.Book; import com.hd.SAXHd; public class saxWrite { public ArrayList<Book> parseXml() throws ParserConfigurationException, SAXException, IOException{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); SAXHd hd = new SAXHd(); parser.parse("books.xml", hd); return hd.getBookList(); } public void creatXML() throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException { ArrayList<Book> book = parseXml();//运行parseXml,将一个包含两本书对象的集合传给变量book; SAXTransformerFactory tff = (SAXTransformerFactory)SAXTransformerFactory.newInstance();//创建SAXTransformerFactory对象 TransformerHandler tfh = tff.newTransformerHandler();//创建TransformerHandler对象; Transformer tf = tfh.getTransformer();//通过TransformerHandler创建Transformer对象; tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//通过Transformer对象设置编码; tf.setOutputProperty(OutputKeys.INDENT, "YES");//通过Transformer对象设置是否换行; File f = new File("books02.xml"); if(!f.exists()) { f.createNewFile(); } Result result = new StreamResult(new FileOutputStream(f));//将文件加载到result中 tfh.setResult(result);//将创建好的result对象和TransformerHandler对象关联 tfh.startDocument();//打开文档 AttributesImpl attr = new AttributesImpl(); tfh.startElement("", "", "bookstore", attr); for (Book i :book) { attr.clear(); attr.addAttribute("", "", "id", "", i.getId()); tfh.startElement("","","book",attr); if(i.getName()!=null && !i.getName().trim().equals("")) { attr.clear(); tfh.startElement("","","name",attr); tfh.characters(i.getName().toCharArray(), 0, i.getName().length()); tfh.endElement("","","name");} if(i.getAuthor()!=null && !i.getAuthor().trim().equals("")) { attr.clear(); tfh.startElement("","","author",attr); tfh.characters(i.getAuthor().toCharArray(), 0, i.getAuthor().length()); tfh.endElement("","","author");} if(i.getYear()!=null && !i.getYear().trim().equals("")) { attr.clear(); tfh.startElement("","","year",attr); tfh.characters(i.getYear().toCharArray(), 0, i.getYear().length()); tfh.endElement("","","year");} tfh.endElement("","","book"); } tfh.endElement("", "", "bookstore"); tfh.endDocument();//关闭文档 } public static void main(String[] args) throws TransformerConfigurationException, ParserConfigurationException, SAXException, IOException { // TODO Auto-generated method stub saxWrite test = new saxWrite(); test.creatXML(); } }
dom4j创建rss类的xml文件:
package com.writexml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class dom4j { public void creatMXL() throws IOException { Document document = DocumentHelper.createDocument();//创建document对象,代表整个xml文档 Element rss = document.addElement("rss");//创建根节点rss; rss.addAttribute("version", "2.0");//向根节点添加属性 Element channel = rss.addElement("channel");//生成rss的子节点channel Element title = channel.addElement("title");//生成channel的子节点title title.setText("国内最新新闻");//设置子节点title的节点值 OutputFormat format = OutputFormat.createPrettyPrint();//设置格式 format.setEncoding("GBK");//设置字符编码 File file = new File("books03.xml"); XMLWriter writer = new XMLWriter(new FileOutputStream(file),format); writer.setEscapeText(false);//设置是否转义,默认是会转义 writer.write(document);//生成xml文件并传进格式 writer.close(); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub dom4j test = new dom4j(); test.creatMXL(); } }
JDOM生成xml文件
package com.writexml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.EscapeStrategy; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class jdomWriter { EscapeStrategy es = new EscapeStrategy() { @Override public boolean shouldEscape(char arg0) { // TODO Auto-generated method stub return false; } }; public void creatXML() throws FileNotFoundException, IOException { Element rss = new Element("rss");//创建rss根节点 rss.setAttribute("servion", "2.0");//创建节点的属性 Document document = new Document(rss);//生成document对象,并将根节点传入 Element channel = new Element("channel"); rss.addContent(channel); Element title = new Element("title"); title.setText("国内最新新闻"); channel.addContent(title); Format format = Format.getPrettyFormat(); format.setEscapeStrategy(es ); XMLOutputter outputer = new XMLOutputter(format);//创建outputer对象 File file = new File("books04.xml"); outputer.output(document, new FileOutputStream(file));//通过outputer对象中的output方法将document对象传入xml文件中 } public static void main(String[] args) throws FileNotFoundException, IOException { // TODO Auto-generated method stub jdomWriter test = new jdomWriter(); test.creatXML(); } }