Java读取xml文件

转 :http://blog.csdn.net/zlp5201/article/details/7163683

写了一篇xml的文章,点发布发表不上,点舍去就他妈的一下子全没了,连回收站和草稿箱都没有了,真不知道怎么想CSDN 

参考http://blog.csdn.net/yangzl2008/article/details/7045369

废话不多说了,贴代码:

[java] view plain copy
 
 print?
  1. /** 
  2.  *  
  3.  */  
  4. package com.zlp.test.xml;  
  5.   
  6. import java.io.File;  
  7. import java.util.Iterator;  
  8.   
  9. import javax.xml.parsers.DocumentBuilder;  
  10. import javax.xml.parsers.DocumentBuilderFactory;  
  11. import javax.xml.parsers.SAXParser;  
  12. import javax.xml.parsers.SAXParserFactory;  
  13.   
  14. import org.dom4j.DocumentException;  
  15. import org.dom4j.Element;  
  16. import org.dom4j.io.SAXReader;  
  17. import org.w3c.dom.Document;  
  18. import org.w3c.dom.Node;  
  19. import org.w3c.dom.NodeList;  
  20. import org.xml.sax.Attributes;  
  21. import org.xml.sax.InputSource;  
  22. import org.xml.sax.SAXException;  
  23. import org.xml.sax.helpers.DefaultHandler;  
  24.   
  25.   
  26. /** 
  27.  * @author Administrator 
  28.  * 
  29.  */  
  30. public class XmlRead extends DefaultHandler{  
  31.   
  32.     /** 
  33.      * @param args 
  34.      */  
  35.     /* 
  36.      * DOM 
  37.      */  
  38.     public void TestDOM(){  
  39.         DocumentBuilderFactory factory = DocumentBuilderFactory     
  40.         .newInstance();  
  41.         Document doc = null;  
  42.         try {  
  43.             DocumentBuilder builder = factory.newDocumentBuilder();  
  44.             doc = builder.parse(new File("test.xml"));  
  45.         } catch (Exception e) {  
  46.             e.printStackTrace();  
  47.         }   
  48.           
  49.         String str = doc.getElementsByTagName("name").item(0).getFirstChild().getNodeValue().trim();  
  50.         System.out.println(str);  
  51.     }  
  52.   
  53.     /* 
  54.      * dom4j 
  55.      */  
  56.     public void Dom4jReadTest(){  
  57.         File f = new File("test.xml");  
  58.         SAXReader saxReader = new SAXReader();  
  59.         org.dom4j.Document document = null;  
  60.          try {  
  61.             document = saxReader.read(f);  
  62.         } catch (DocumentException e) {  
  63.             // TODO Auto-generated catch block  
  64.             e.printStackTrace();  
  65.         }  
  66.         Element rootElement = document.getRootElement();  
  67.         Iterator iterator = rootElement.elementIterator("node");  
  68.           
  69.         for (; iterator.hasNext();) {  
  70.             Element other = (Element)iterator.next();  
  71.             System.out.println(other.elementTextTrim("name"));  
  72.         }  
  73.     }  
  74.       
  75.     public void SAX(){  
  76.         java.util.Stack tags = new java.util.Stack();     
  77.         SAXParserFactory saxparserfactory = SAXParserFactory.newInstance();  
  78.         try {  
  79.             SAXParser parser = saxparserfactory.newSAXParser();  
  80.             parser.parse(new InputSource("test.xml"), new XmlRead());  
  81.           
  82.         } catch (Exception e) {  
  83.             // TODO Auto-generated catch block  
  84.             e.printStackTrace();  
  85.         }  
  86.     }  
  87.         java.util.Stack tags = new java.util.Stack();  
  88.         public void startElement(String uri, String localName, String qName,Attributes attrs) {  
  89.             tags.push(qName);  
  90.         }  
  91.       
  92.       public void characters(char ch[], int start, int length)  
  93.         throws SAXException {  
  94.   
  95.           String tag = (String) tags.peek();  
  96.             if (tag.equals("name")) {  
  97.                   System.out.print("name" + new String(ch, start, length));  
  98.             }  
  99.             if (tag.equals("space")) {  
  100.                   System.out.println("space:" + new String(ch, start, length));  
  101.             }  
  102. }  
  103.   
  104.       
  105.       
  106.     public static void main(String[] args) {  
  107.         //new XmlRead().TestDOM();  
  108.         new XmlRead().Dom4jReadTest();  
  109.         //new XmlRead().SAX();  
  110.     }  
  111.       
  112.       
  113.   
  114. }  


test.xml文件

[html] view plain copy
 
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <list>  
  3.  <node>  
  4.   <name>  
  5.    weidewei  
  6.   </name>  
  7.   <space>  
  8.    http://wishlife.iteye.com  
  9.   </space>  
  10.  </node>  
  11. </list>  


Sax解析xml

[java] view plain copy
 
 print?
  1. package com.zlp.test.xml;  
  2.   
  3. import java.io.File;   
  4. import java.util.Vector;   
  5.   
  6. import org.xml.sax.Attributes;   
  7. import org.xml.sax.SAXException;   
  8. import org.xml.sax.helpers.DefaultHandler;   
  9.   
  10. import javax.xml.parsers.SAXParser;   
  11. import javax.xml.parsers.SAXParserFactory;   
  12.   
  13. public class PraseXML extends DefaultHandler   
  14. {   
  15.   
  16.   private Vector<String> tagName;   
  17.   
  18.   private Vector<String> tagValue;   
  19.   
  20.   private int step;   
  21.   // 开始解析XML文件   
  22.   public void startDocument() throws SAXException   
  23.   {   
  24.     tagName = new Vector<String>();   
  25.     tagValue = new Vector<String>();   
  26.     step = 0;   
  27.   }   
  28.   // 结束解析XML文件   
  29.   public void endDocument() throws SAXException   
  30.   {   
  31.     for (int i = 0; i < tagName.size(); i++)   
  32.     {   
  33.       if (!tagName.get(i).equals("") || tagName.get(i) != null)   
  34.       {   
  35.         System.out.println("节点名称:" + tagName.get(i));   
  36.         System.out.println("节点值:" + tagValue.get(i));   
  37.       }   
  38.     }   
  39.   }   
  40.   /**  
  41.     * 在解释到一个开始元素时会调用此方法.但是当元素有重复时可以自己写算法来区分  
  42.     * 这些重复的元素.qName是什么? <name:page ll=""></name:page>这样写就会抛出SAXException错误  
  43.     * 通常情况下qName等于localName  
  44.     */   
  45.   public void startElement(String uri, String localName, String qName,   
  46.       Attributes attributes) throws SAXException   
  47.   {   
  48.     // 节点名称   
  49.     tagName.add(qName);   
  50.     // 循环输出属性   
  51.     for (int i = 0; i < attributes.getLength(); i++)   
  52.     {   
  53.       // 获取属性名称   
  54.       System.out.println("属性名称:" + attributes.getQName(i));   
  55.       // 获取属性值   
  56.       System.out.println("属性值:"   
  57.           + attributes.getValue(attributes.getQName(i)));   
  58.     }   
  59.   
  60.   }   
  61.   
  62.   /**  
  63.     * 在遇到结束标签时调用此方法  
  64.     */   
  65.   public void endElement(String uri, String localName, String qName)   
  66.       throws SAXException   
  67.   {   
  68.   
  69.     step = step + 1;   
  70.   }   
  71.   
  72.   /**  
  73.     * 读取标签里的值,ch用来存放某行的xml的字符数据,包括标签,初始大小是2048,  
  74.     * 每解释到新的字符会把它添加到char[]里。    * 注意,这个char字符会自己管理存储的字符,  
  75.     * 并不是每一行就会刷新一次char,start,length是由xml的元素数据确定的,  
  76.     * 暂时找不到规律,以后看源代码.  
  77.     *     
  78.     * 这里一个正标签,反标签都会被执行一次characters,所以在反标签时不用获得其中的值  
  79.     */   
  80.   public void characters(char ch[], int start, int length)   
  81.       throws SAXException   
  82.   {   
  83.     // 只要当前的标签组的长度一至,值就不赋,则反标签不被计划在内   
  84.     if (tagName.size() - 1 == tagValue.size())   
  85.     {   
  86.       tagValue.add(new String(ch, start, length));   
  87.     }   
  88.   }   
  89.   
  90.   public static void main(String[] args)   
  91.   {   
  92.     String filename = "test.xml";   
  93.     SAXParserFactory spf = SAXParserFactory.newInstance();   
  94.     try   
  95.     {   
  96.       SAXParser saxParser = spf.newSAXParser();   
  97.       saxParser.parse(new File(filename), new PraseXML());   
  98.     }   
  99.     catch (Exception e)   
  100.     {   
  101.       e.printStackTrace();   
  102.     }   
  103.   }   
  104.   public Vector getTagName()   
  105.   {   
  106.     return tagName;   
  107.   }   
  108.   public void setTagName(Vector tagName)   
  109.   {   
  110.     this.tagName = tagName;   
  111.   }   
  112.   public Vector getTagValue()   
  113.   {   
  114.     return tagValue;   
  115.   }   
  116.   
  117.   public void setTagValue(Vector tagValue)   
  118.   {   
  119.     this.tagValue = tagValue;   
  120.   }   
  121.   
  122. }   


在贴上一个simplejee中读取xml的文件。

[java] view plain copy
 
 print?
  1. package com.yuqiaotech.simplejee.xml;  
  2.   
  3. import java.io.File;    
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStreamWriter;  
  8. import java.io.Writer;  
  9. import java.util.Iterator;    
  10.     
  11. import javax.xml.parsers.DocumentBuilder;    
  12. import javax.xml.parsers.DocumentBuilderFactory;    
  13. import javax.xml.parsers.ParserConfigurationException;  
  14. import javax.xml.parsers.SAXParser;    
  15. import javax.xml.parsers.SAXParserFactory;    
  16. import javax.xml.transform.OutputKeys;  
  17. import javax.xml.transform.Transformer;  
  18. import javax.xml.transform.TransformerConfigurationException;  
  19. import javax.xml.transform.TransformerException;  
  20. import javax.xml.transform.TransformerFactory;  
  21. import javax.xml.transform.dom.DOMSource;  
  22. import javax.xml.transform.stream.StreamResult;  
  23. import javax.xml.transform.stream.StreamSource;  
  24.     
  25. import org.dom4j.DocumentException;  
  26. import org.dom4j.io.OutputFormat;  
  27. import org.dom4j.io.SAXReader;    
  28. import org.dom4j.io.XMLWriter;  
  29. import org.w3c.dom.Document;    
  30. import org.w3c.dom.NamedNodeMap;  
  31. import org.w3c.dom.Node;  
  32. import org.w3c.dom.NodeList;    
  33. import org.xml.sax.Attributes;    
  34. import org.xml.sax.SAXException;    
  35. import org.xml.sax.helpers.DefaultHandler;    
  36.   
  37. import com.sun.org.apache.xpath.internal.XPathAPI;  
  38. /** 
  39.  * 大体代码是从http://www.javaeye.com/topic/181865抄来的。 
  40.  * 下面这个是被广泛抄袭的,关于java里读取xml的概要介绍。 
  41.  * http://blog.csdn.net/geekwang/archive/2008/05/25/2480504.aspx  
  42.  *  
  43.  * 我主要是把从绝对路径读取xml换成了从classpath读取。 
  44.  * 另外添加了Transformer和xslt,以及XPath的演示,以及相关的一些链接。 
  45.  *  
  46.  * 另外可以搜一下jaxp了解这个规范的相关内容。 
  47.  *  
  48.  * @author YUQIAOTECH 
  49.  * 
  50.  */  
  51. public class SimpleSample  {    
  52.   static String xmlName = "test.xml";  
  53.   static String xlst = "xslt.xsl";  
  54.   static String dom4jSaveTo = "c:/text.xml";  
  55.   static String xsltSaveTo = "c:/text2.html";  
  56.     
  57.   
  58.     /**  
  59.      * DOM方式  
  60.      */    
  61.     public void DOM() {    
  62.         long lasting = System.currentTimeMillis();    
  63.     
  64.         try {    
  65.             InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  66.             DocumentBuilderFactory factory = DocumentBuilderFactory    
  67.                     .newInstance();  
  68.             DocumentBuilder builder = factory.newDocumentBuilder();    
  69.             Document doc = builder.parse(in); //注意这里的Document是org.w3c.dom包下的  
  70.             NodeList nl = doc.getElementsByTagName("node");    
  71.             for (int i = 0; i < nl.getLength(); i++) {    
  72.                 System.out.println("|| Name:  |"    
  73.                         + doc.getElementsByTagName("name").item(i)    
  74.                                 .getFirstChild().getNodeValue());    
  75.                 System.out.println("||Space:  |"    
  76.                         + doc.getElementsByTagName("space").item(i)    
  77.                                 .getFirstChild().getNodeValue());    
  78.                 System.out.println("-------------------------------------------------");            }    
  79.         } catch (Exception e) {    
  80.             e.printStackTrace();    
  81.         }    
  82.         System.out.println("耗时:"    
  83.                 + (System.currentTimeMillis() - lasting) + " MS");    
  84.     }    
  85.     
  86.     class SaxHandler extends DefaultHandler{  
  87.         java.util.Stack tags = new java.util.Stack();    
  88.         public void startElement(String uri, String localName, String qName,    
  89.                 Attributes attrs) {    
  90.             tags.push(qName);    
  91.         }    
  92.         
  93.         public void characters(char ch[], int start, int length)    
  94.                 throws SAXException {    
  95.             String tag = (String) tags.peek();    
  96.             if (tag.equals("name")) {    
  97.                 System.out.println("|| Name:  |" + new String(ch, start, length));    
  98.             }    
  99.             if (tag.equals("space")) {    
  100.                 System.out.println("||Space:  |" + new String(ch, start, length));    
  101.             }    
  102.             System.out.println("-------------------------------------------------");    
  103.         }    
  104.     }  
  105.     
  106.     /**  
  107.      * SAX方式  
  108.      */    
  109.     public void SAX() {    
  110.     
  111.         long lasting = System.currentTimeMillis();    
  112.         try {    
  113.             InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  114.             SAXParserFactory sf = SAXParserFactory.newInstance();    
  115.             SAXParser sp = sf.newSAXParser();    
  116.             SaxHandler reader = new SaxHandler();    
  117.             sp.parse(in, reader);    
  118.         } catch (Exception e) {    
  119.             e.printStackTrace();    
  120.         }    
  121.         System.out.println("SAX 耗时:"    
  122.                 + (System.currentTimeMillis() - lasting) + " MS");    
  123.     }    
  124.     
  125.   
  126.     
  127.     /**  
  128.      * 我懒得去了解JDOM了 :-)。 
  129.      * JDOM方式  
  130.      */    
  131. //    public void JDOM() {    
  132. //        long lasting = System.currentTimeMillis();    
  133. //        try {    
  134. //            SAXBuilder builder = new SAXBuilder();    
  135. //            org.jdom.Document doc = builder.build(new File("F:/xmltest.xml"));    
  136. //            Element foo = doc.getRootElement();    
  137. //            List allChildren = foo.getChildren();    
  138. //            for (int i = 0; i < allChildren.size(); i++) {    
  139. //                System.out.println("|| Name:  |"    
  140. //                        + ((Element) allChildren.get(i)).getChild("name")    
  141. //                                .getText());    
  142. //                System.out.println("||Space:  |"    
  143. //                        + ((Element) allChildren.get(i)).getChild("space")    
  144. //                                .getText());    
  145. //                System.out.println("-------------------------------------------------");            }    
  146. //        } catch (Exception e) {    
  147. //            e.printStackTrace();    
  148. //        }    
  149. //        System.out.println("JDOM RUNTIME:"    
  150. //                + (System.currentTimeMillis() - lasting) + " MS");    
  151. //    }    
  152.     
  153.     /**  
  154.      * DOM4J方式  
  155.      */    
  156.     public void DOM4J() {    
  157.         long lasting = System.currentTimeMillis();    
  158.         try {    
  159.             InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  160.             SAXReader reader = new SAXReader();    
  161.             org.dom4j.Document doc = reader.read(in);  //注意这里的Document是org.dom4j包下的  
  162.             org.dom4j.Element root = doc.getRootElement();    
  163.             org.dom4j.Element foo;    
  164.             for (Iterator i = root.elementIterator("node"); i.hasNext();) {    
  165.                 foo = (org.dom4j.Element) i.next();    
  166.                 System.out.println("|| Name:  |" + foo.elementText("name"));    
  167.                 System.out.println("||Space:  |" + foo.elementText("space"));    
  168.                 System.out.println("-------------------------------------------------");    
  169.             }    
  170.         } catch (Exception e) {    
  171.             e.printStackTrace();    
  172.         }    
  173.         System.out.println("DOM4J 耗时:"    
  174.                 + (System.currentTimeMillis() - lasting) + " MS");    
  175.     }  
  176.     /** 
  177.      * 调用dom4j的保存方法。 
  178.      *  
  179.      * @throws DocumentException 
  180.      * @throws IOException 
  181.      */  
  182.     public static void saveDocByDom4J() throws DocumentException, IOException{  
  183.         Writer out = new OutputStreamWriter(new FileOutputStream(dom4jSaveTo ),"GBK");  
  184.         OutputFormat format = OutputFormat.createPrettyPrint();  
  185.         XMLWriter writer = new XMLWriter( out, format );  
  186.         InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  187.         SAXReader reader = new SAXReader();    
  188.         org.dom4j.Document doc = reader.read(in);    
  189.         writer.write( doc );  
  190.         out.close();  
  191.     }  
  192.   
  193.     /** 
  194.      * 使用Transformer和xslt。 
  195.      * http://www.ibm.com/developerworks/cn/xml/x-xslt/ 
  196.      *  
  197.      * @throws ParserConfigurationException 
  198.      * @throws SAXException 
  199.      * @throws IOException 
  200.      */  
  201.     public static void saveByTransformer() throws ParserConfigurationException, SAXException, IOException {  
  202.         try {  
  203.             InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  204.             InputStream inXsl = SimpleSample.class.getResourceAsStream(xlst);   
  205.             DocumentBuilderFactory factory = DocumentBuilderFactory    
  206.                     .newInstance();    
  207.             DocumentBuilder builder = factory.newDocumentBuilder();    
  208.             Document doc = builder.parse(in);   
  209.             StreamSource style = new StreamSource(inXsl);   
  210.             TransformerFactory tFactory = TransformerFactory.newInstance();  
  211.             Transformer transformer = tFactory.newTransformer(style);  
  212.             transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");  
  213.             DOMSource source = new DOMSource(doc);  
  214.             StreamResult result = new StreamResult(new File(xsltSaveTo));  
  215.             transformer.transform(source, result);  
  216.         } catch (TransformerConfigurationException e) {  
  217.             throw new RuntimeException(e.getMessage(), e);  
  218.         } catch (TransformerException e) {  
  219.             throw new RuntimeException(e.getMessage(), e);  
  220.         }  
  221.     }  
  222.       
  223.     //**********************XPath*****************************  
  224.       
  225.     /**  
  226.      * 返回指定的节点。  
  227.      *   
  228.      * @param topNode  
  229.      * @param xPath  
  230.      * @return  
  231.      */  
  232.     public static Node selectSingleNode(Node topNode, String xPath) {  
  233.         try {  
  234.             return XPathAPI.selectSingleNode(topNode, xPath);  
  235.         } catch (TransformerException e) {  
  236.             System.out.println(e.getMessage() + " xPath=" + xPath);  
  237.             throw new RuntimeException(e.getMessage(), e);  
  238.         }  
  239.     }  
  240.   
  241.     /** 
  242.      * 根据属性名获取属性节点。 
  243.      *  
  244.      * @param node 
  245.      * @param attributeName 
  246.      * @return 
  247.      */  
  248.     public static Node getAttributeNode(Node node, String attributeName) {  
  249.         NamedNodeMap namedNodeMap = node.getAttributes();  
  250.         return namedNodeMap.getNamedItem(attributeName);  
  251.     }  
  252.   
  253.     /** 
  254.      * 几个方法的组合。 
  255.      *  
  256.      * @param node 
  257.      * @param xPath 
  258.      * @param attributeName 
  259.      * @return 
  260.      */  
  261.     public static String getAttributeNodeByXPath(Node node, String xPath,  
  262.             String attributeName) {  
  263.         Node rtn = null;  
  264.         Node selectedNode = selectSingleNode(node, xPath);  
  265.         if (selectedNode != null) {  
  266.             rtn = getAttributeNode(selectedNode, attributeName);  
  267.         }  
  268.         if(rtn == null)return null;  
  269.         return rtn.getNodeValue();  
  270.     }  
  271.     /** 
  272.      * http://www.zvon.org/xxl/XPathTutorial/General_chi/examples.html 
  273.      * http://www.ibm.com/developerworks/cn/xml/x-wxxm35.html 
  274.      *  
  275.      * @throws ParserConfigurationException 
  276.      * @throws SAXException 
  277.      * @throws IOException 
  278.      */  
  279.     public static void XPath() throws ParserConfigurationException, SAXException, IOException{  
  280.         InputStream in = SimpleSample.class.getResourceAsStream(xmlName);   
  281.         DocumentBuilderFactory factory = DocumentBuilderFactory    
  282.                 .newInstance();    
  283.         DocumentBuilder builder = factory.newDocumentBuilder();    
  284.         Document doc = builder.parse(in);   
  285.         String attr = getAttributeNodeByXPath(doc,"//node[@id=1]/name","alias");  
  286.         System.out.println("alias="+attr);  
  287.           
  288.     }  
  289.     public static void main(String arge[]) throws ParserConfigurationException, SAXException, IOException, DocumentException {    
  290.         SimpleSample myXML = new SimpleSample();    
  291.         System.out.println("=====================DOM=========================");    
  292.         myXML.DOM();    
  293.         System.out.println("=====================SAX=========================");    
  294.         myXML.SAX();    
  295.         //System.out.println("=====================JDOM========================");    
  296.         //myXML.JDOM();    
  297.         System.out.println("=====================DOM4J=======================");    
  298.         myXML.DOM4J();    
  299.         System.out.println("=====================DOM4J的格式化保存=======================");     
  300.         saveDocByDom4J();  
  301.         System.out.println("=====================Transformer和xslt的使用=======================");    
  302.         saveByTransformer();  
  303.         System.out.println("=====================XPath的演示=======================");   
  304.         XPath();  
  305.     }    
  306. }    


test1.xml

[html] view plain copy
 
 print?
  1. <?xml version="1.0" encoding="gbk"?>  
  2. <list>  
  3.  <node id="1"><name alias="李逵">张三</name><space>http://wishlife.javaeye.com</space></node>  
  4.  <node><name>李四</name><space>http://user.qzone.qq.com/94611981</space></node>  
  5. </list>    


xslt.xsl

[html] view plain copy
 
 print?
  1. <xsl:transform  
  2. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  
  3. version="1.0">  
  4. <xsl:variable name="nodes" select="//node"/>  
  5. <xsl:template match="list">  
  6. <html><body>  
  7.  <h1>名单</h1>  
  8.  <table cellpadding="5">  
  9.  <tr>  
  10.  <td>姓名</td>  
  11.  <td>博客</td>  
  12.  </tr>  
  13.  <xsl:for-each select="$nodes">  
  14.  <tr>  
  15.  <td<xsl:value-of select="./name"/>(<xsl:value-of select="./name/@alias"/>)</td>  
  16.  <td<xsl:value-of select="./space"/></td>  
  17.  </tr>  
  18.  </xsl:for-each>  
  19.  </table>  
  20. </body></html>  
  21. </xsl:template>  
  22. </xsl:transform>  



 

 
 
posted @ 2017-04-19 11:46  xuyatao  阅读(7925)  评论(0编辑  收藏  举报