java xml学习总结

xml学习

 一. 概述

      xml的四种解析方式:

            1.  以DOM方式解析。优点是可以对文档的内容和结构进行修改,但不适合大文件的读取。

            2.  以SAX方式解析。SAX模型最大的优点是内存消耗小,因为整个文档无需一次加载到内存中,这使SAX解析器可以解析大于系统内存的文档。缺点是不能修改文档。

               3.   通过JDOM组件。可以认为JDOM=DOM+SAX,折合了两种的优点。

               4.    通过DOM4j组件。跟JDOM类似,某些时候由于JDOM,常见于一些开源框架中。

 

二. DOM

使用案例:

       1.读取文档

                     <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOMDemo{ public static void main(String[] args) { //取得DocmentBuilderFactory对象 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); //取得DocumentBuilder对象 DocumentBuilder builder=null; try { builder=factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } //取得Document对象 Document doc=null; try { doc=builder.parse(new File("DOMDemo.xml")); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nl=doc.getElementsByTagName("man"); for(int i=0;i<nl.getLength();i++){ Element e=(Element) nl.item(i); System.out.println(e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); System.out.println(e.getElementsByTagName("age").item(0).getFirstChild().getNodeValue()); } } } </span> 

      2.写入xml文档

                    <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; 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; public class GenerateXMLDemo { public static void main(String[] args) { // TODO Auto-generated method stub DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=null; try { builder=factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc=null; doc=builder.newDocument(); //建立各个操作节点 Element mans=doc.createElement("mans"); Element man=doc.createElement("man"); Element name=doc.createElement("name"); Element age=doc.createElement("age"); //为节点添加内容 name.appendChild(doc.createTextNode("罗军平")); age.appendChild(doc.createTextNode("22")); //设置节点关系 man.appendChild(name); man.appendChild(age); mans.appendChild(man); doc.appendChild(mans); //输出到文档文件中中 TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer tf=null; try { tf=tfactory.newTransformer(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } //tf.setOutputProperty(OutputKeys.ENCODING,"GBK");//设置编码 DOMSource source=new DOMSource(doc); StreamResult result=new StreamResult(new File("GenerateXMLDemo.xml")); try { tf.transform(source, result); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span> 

 三. SAX

       SAX的一个特点是用户可以自定义的输出内容的格式,此功能的实现要求用户用户设计一个类,此类需继承DefaultHandler,并复写相关方法,如下面的MySAX类

使用案例:

 

          1.读取xml文档:    

                 MySAX.java

                <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MySAX extends DefaultHandler { public void startDocument() throws SAXException{ System.out.print("<?xml version=/"1.0/" encoding=/"GBK/"?>"); } public void startElement(String uri,String localName, String qName,Attributes arributes)throws SAXException{ System.out.print("<"); System.out.print(qName); System.out.print(">"); } public void characters(char[] ch,int start,int length) throws SAXException{ System.out.print(new String(ch,start,length)); } public void endElement(String uri,String localName, String qName)throws SAXException{ System.out.print("<"); System.out.print(qName); System.out.print(">"); } public void endDocument() throws SAXException{ System.out.print("文档结束。。。。"); } } </span> 

                SAXDemo.java

                <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; public class SAXDemo { public static void main(String args[]){ SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=null; try { parser = factory.newSAXParser(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { parser.parse(new File("SAXDemo.xml"),new MySAX()); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span>   

四. JDOM

使用案例:

       1.读取xml文档 

            JDOMParseDemo.java 

            <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class JDOMParseDemo { public static void main(String[] args) { SAXBuilder builder=new SAXBuilder(); Document doc=null; try { doc=builder.build(new File("JDOMWriteDemo.xml")); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //得到跟节点 Element root=doc.getRootElement(); List list=root.getChildren(); Iterator iter=list.iterator(); while(iter.hasNext()){ Element e=(Element) iter.next(); String name=e.getChildText("name"); String id=e.getChild("name").getAttributeValue("id"); String age=e.getChildText("age"); System.out.print(name+" "+id+" "+age); } } } </span>    

        2.创建xml文档

          JDOMWriteDemo .java 

              <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; public class JDOMWriteDemo { public static void main(String[] args) { // TODO Auto-generated method stub Document doc=new Document(); Element mans=new Element("mans"); Element man=new Element("man"); Element name=new Element("name"); Element age=new Element("age"); Attribute id=new Attribute("id","罗军平"); //增加内容 name.setText("罗军平"); age.setText("22"); name.setAttribute(id); //设置联系 doc.addContent(mans); mans.addContent(man); man.addContent(name); man.addContent(age); //输出到文件 XMLOutputter out=new XMLOutputter(); try { out.setFormat(out.getFormat().setEncoding("GBK")); //设置编码 out.output(doc,new FileOutputStream(new File("JDOMWriteDemo.xml"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span> 

 五. DOM4j

使用案例:

         1.读取xml文档 

                   DOM4jReaderDemo.java

                  <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DOM4jReaderDemo { /** * @param args */ public static void main(String[] args) { SAXReader reader=new SAXReader(); Document doc=null; try { doc=reader.read(new File("DOM4jWriteDemo.xml")); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root=doc.getRootElement(); Iterator iter=root.elementIterator("man"); while(iter.hasNext()){ Element man=(Element) iter.next(); System.out.println(man.elementText("name")); System.out.println(man.elementText("age")); } } } </span>  

          2.创建xml文档  

                    DOM4jWriteDemo.java

                   <span style="font-size: small;" mce_style="font-size: small;">package com.ljp.xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class DOM4jWriteDemo { @SuppressWarnings("deprecation") public static void main(String[] args) { Document doc=DocumentHelper.createDocument(); //定义一个根节点 Element root=doc.addElement("mans"); Element man=root.addElement("man"); Element name=man.addElement("name"); Element age=man.addElement("age"); name.setText("Tom"); //name.setAttributeValue("id", "luo"); //已过时 name.addAttribute("id", "20091205"); age.setText("22"); OutputFormat format=OutputFormat.createPrettyPrint(); format.setEncoding("GBK"); XMLWriter writer=null; try { writer=new XMLWriter(new FileOutputStream(new File("DOM4jWriteDemo.xml")),format); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { writer.write(doc); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span> 

你可能感兴趣的:(java,xml,String,iterator,Class,文档)