package SAX; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import handler.SaxParserHandler; import javax.naming.spi.DirStateFactory.Result; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; 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.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import Entity.Book; public class SaxTest { public static void main(String[] args) { // TODO Auto-generated method stub SaxTest st=new SaxTest(); // st.parseXML(); st.createXML(); } public ArrayList<Book> parseXML(){ //获取一个SAXParserFactory的实例 SAXParserFactory factory=SAXParserFactory.newInstance(); SaxParserHandler handler=null; try { //通过factory获取一个saxpaser的实例 SAXParser parser=factory.newSAXParser(); //uri是路径 创建SAXhandler对象 handler=new SaxParserHandler(); parser.parse("新建文本文档.xml", handler); // System.out.println(handler.getBooklist().size()); // for (Book book : handler.getBooklist()) { // System.out.println(book.getAuthor()); // System.out.println("====完成===="); // } } 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(); } return handler.getBooklist(); } public void createXML(){ ArrayList<Book> booklist =parseXML(); //生成xml //创建一个SAXtransformerfactory对象 SAXTransformerFactory tff=(SAXTransformerFactory) SAXTransformerFactory.newInstance(); try { //创建transforemerhandler对象。 TransformerHandler handler= tff.newTransformerHandler(); //创建transformer对象 Transformer tr= handler.getTransformer(); //通过transformer对xml文件进行设置 tr.setOutputProperty(OutputKeys.ENCODING, "utf-8"); //设置编码 必须在setresult之前 tr.setOutputProperty(OutputKeys.INDENT, "yes"); //设置换行 //创建result对象 File f= new File("src/res/books.xml"); if(!f.exists()){ try { f.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //创建result对象并且使其与handler关联 javax.xml.transform.Result result=new StreamResult(new FileOutputStream(f)); handler.setResult(result); //利用handler对xml文件进行内容的编写 //打开document handler.startDocument(); AttributesImpl attr=new AttributesImpl(); //startelement是创建的节点 characters是创建节点的值 handler.startElement("", "", "bookstore", attr); for (Book book : booklist) { attr.clear(); attr.addAttribute("", "", "id", "", book.getId()); handler.startElement("", "", "book", attr); attr.clear(); handler.startElement("", "", "name", attr); handler.characters(book.getName().toCharArray(),0 ,book.getName().length() ); handler.endElement("", "", "name"); attr.clear(); handler.startElement("", "", "year", attr); handler.characters(book.getYear().toCharArray(),0 ,book.getYear().length() ); handler.endElement("", "", "year"); attr.clear(); handler.startElement("", "", "author", attr); handler.characters(book.getAuthor().toCharArray(),0 ,book.getAuthor().length() ); handler.endElement("", "", "author"); handler.endElement("", "", "book"); } handler.endElement("", "", "bookstore"); //关闭document handler.endDocument(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /*还报错了 com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence. at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:684) at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:554) at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1742) at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(XMLEntityScanner.java:487) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2687) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522) at javax.xml.parsers.SAXParser.parse(SAXParser.java:395) at javax.xml.parsers.SAXParser.parse(SAXParser.java:277) at SAX.SaxTest.parseXML(SaxTest.java:46) at SAX.SaxTest.createXML(SaxTest.java:66) at SAX.SaxTest.main(SaxTest.java:33) */
public void SAXWriteXml() { List<Book> bookList = SAXReadXml(); // 1 创建SAXTransformerFactory类的对象 SAXTransformerFactory stff = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); try { // 2通过SAXTransformerFactory对象创建一个TransformerHandler对象 TransformerHandler handler = stff.newTransformerHandler(); // 3通过handler创建Transformer对象 Transformer tf = handler.getTransformer(); // 4通过Transformer对象对生成的xml文件进行设置 tf.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 5创建一个Result对象 File file = new File("source/shuji.xml"); if (!file.exists()) { file.createNewFile(); } // 6创建Result对象,result与handler关联 Result result = new StreamResult(new FileOutputStream(file)); handler.setResult(result); // 7利用Handler对象进行xml文件内容的填充 // 打开document文档 handler.startDocument(); AttributesImpl atts = new AttributesImpl(); handler.startElement("", "", "bookstore", atts); for (Book book : bookList) { atts.clear(); atts.addAttribute("", "", "id", "", book.getId()); handler.startElement("", "", "book", atts); atts.clear(); // 创建name节点 if ((book.getName() != null) && !book.getName().trim().equals("")) { atts.clear(); System.out.println("+++++name+++++"); handler.startElement("", "", "name", atts);//这里没有执行 System.out.println("+++++name+++++"); handler.characters(book.getName().toCharArray(), 0, book .getName().length()); handler.endElement("", "", "name"); } if (!book.getAuthor().trim().equals("") && (book.getAuthor() != null)) { atts.clear(); System.out.println("+++++author+++++"); handler.startElement("", "", "author", atts); handler.characters(book.getAuthor().toCharArray(), 0, book .getAuthor().length()); handler.endElement("", "", "author"); } if (!book.getYear().trim().equals("") && (book.getYear() != null)) { atts.clear(); handler.startElement("", "", "year", atts); handler.characters(book.getYear().toCharArray(), 0, book .getYear().length()); handler.endElement("", "", "year"); } if (!book.getPrice().trim().equals("") && (book.getPrice() != null)) { atts.clear(); handler.startElement("", "", "price", atts); handler.characters(book.getPrice().toCharArray(), 0, book .getPrice().length()); handler.endElement("", "", "price"); } if (!book.getLanguage().trim().equals("") && (book.getLanguage() != null)) { atts.clear(); handler.startElement("", "", "language", atts); handler.characters(book.getLanguage().toCharArray(), 0, book.getLanguage().length()); handler.endElement("", "", "language"); } handler.endElement("", "", "book"); } handler.endElement("", "", "bookstore"); // 关闭document handler.endDocument(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } //异常 Exception in thread "main" java.lang.NullPointerException at com.sun.org.apache.xml.internal.serializer.ToStream.writeAttrString(ToStream.java:1967) at com.sun.org.apache.xml.internal.serializer.ToStream.processAttributes(ToStream.java:1947) at com.sun.org.apache.xml.internal.serializer.ToStream.closeStartTag(ToStream.java:2443) at com.sun.org.apache.xml.internal.serializer.ToStream.startElement(ToStream.java:1783) at com.sun.org.apache.xml.internal.serializer.ToUnknownStream.startElement(ToUnknownStream.java:548) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerHandlerImpl.startElement(TransformerHandlerImpl.java:267) at com.live.imooc.test.SAXTest.SAXWriteXml(SAXTest.java:70) at com.live.imooc.test.SAXTest.main(SAXTest.java:31)
上面是我写的函数;报的错误是空指针异常。
上一个回答不好,我在回答一下,改还是那样改
但是逻辑是因为&&是个短路与
if ((book.getLanguage() != null)
&& !book.getLanguage().trim().equals(""))
这样判断首先判断是不是空,如果是空直接整个if就是false了if里的代码就不执行了
if (!book.getLanguage().trim().equals("")
&& (book.getLanguage() != null)){}
这样判断的话程序先会判断book.getLanguage()是不是个空格,用的equals方法
相当于两个对象比较,第一本书都没有Language,怎么和空格比呢,
所以程序直接报了空指针异常,程序就结束了
你的if条件判断有问题
if (!book.getYear().trim().equals("")
&& (book.getYear() != null)){}这样判断是不对的
应该改成
if ((book.getYear() != null)
&& !book.getYear().trim().equals(""))
因为 && 是个短路与判断
你得先判断是不是空再 && 是不是等于空格
name year author 都得改
我根据课程编写SAX方式写入xml文件也报错;在 handler.startElement("", "", "name", attr);这句没有执行,不明原因。