日期:2014-05-20 浏览次数:20857 次
package com.test.xml; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class Dom4JXML { public void createXML() { //用工厂类创建一个document实例 Document doc = DocumentHelper.createDocument(); //创建根元素emps Element rootEle = doc.addElement("emps"); //添加注释 rootEle.addComment("这是一个dom4j生成的xml文件"); //emps根节点下创建一个emp节点 Element empEle = rootEle.addElement("emp"); //emp添加属性id="1" empEle.addAttribute("id", "1"); //emp节点下创建一个name节点 Element nameEle = empEle.addElement("name"); //name节点下创建一个文本节点zhangsan nameEle.setText("zhangsan"); //再为name节点创建一个兄弟节点 Element sexEle = empEle.addElement("sex"); sexEle.setText("man"); //将document中的内容写入文件中 try { Writer out = new FileWriter("F:\\emps.xml"); //格式化输出,类型IE浏览一样 OutputFormat format = OutputFormat.createPrettyPrint(); //OutputFormat format = OutputFormat.createCompactFormat(); format.setEncoding("UTF-8"); //创建写出对象 XMLWriter writer = new XMLWriter(out,format); writer.write(doc); writer.close(); System.out.println("生成emps.xml成功。"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("失败了。"); } } public static void main(String[] args) { new Dom4JXML().createXML(); } }
------解决方案--------------------
然而从xml文件中解析以后的数据收集可以用SAX试试看
我这里有个简单的例子,希望对LZ有用
package com.test.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXParseHandler extends DefaultHandler{ public void startDocument()throws SAXException{ System.out.println("起始文挡"); } public void endDocument()throws SAXException{ System.out.println("结束文挡"); } public void characters(char[] ch,int start,int length)throws SAXException{ String charString=new String(ch,start,length); System.out.println("字符:"+charString); } public void startElement(String namespaceURI,String localName,String qName,Attributes atts)throws SAXException{ System.out.println("起始元素:"+qName); for(int i=0;i<atts.getLength();i++){ System.out.println("属性值:"+atts.getValue(i)); } } public void endElement(String namespaceURI,String localName,String qName)throws SAXException{ System.out.println("结束元素:"+qName); } }
------解决方案--------------------
package com.test.xml; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class Books { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO 自动生成方法存根 SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); parser.parse("booksamp.xml",new SAXParseHandler()); } }