Java读取xml文件

时间:2025-01-29 07:59:31

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

参考/yangzl2008/article/details/7045369

废话不多说了,贴代码:

/**
 * 
 */
package ;

import ;
import ;

import ;
import ;
import ;
import ;

import org.;
import org.;
import org.;
import org.;
import org.;
import org.;
import ;
import ;
import ;
import ;


/**
 * @author Administrator
 *
 */
public class XmlRead extends DefaultHandler{

	/**
	 * @param args
	 */
	/*
	 * DOM
	 */
	public void TestDOM(){
		DocumentBuilderFactory factory = DocumentBuilderFactory   
        .newInstance();
		Document doc = null;
		try {
			DocumentBuilder builder = ();
			doc = (new File(""));
		} catch (Exception e) {
			();
		} 
		
		String str = ("name").item(0).getFirstChild().getNodeValue().trim();
		(str);
	}

	/*
	 * dom4j
	 */
	public void Dom4jReadTest(){
		File f = new File("");
		SAXReader saxReader = new SAXReader();
		org. document = null;
		 try {
			document = (f);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			();
		}
		Element rootElement = ();
		Iterator iterator = ("node");
		
		for (; ();) {
			Element other = (Element)();
			(("name"));
		}
	}
	
	public void SAX(){
		 tags = new ();   
		SAXParserFactory saxparserfactory = ();
		try {
			SAXParser parser = ();
			(new InputSource(""), new XmlRead());
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			();
		}
	}
		 tags = new ();
		public void startElement(String uri, String localName, String qName,Attributes attrs) {
			(qName);
		}
	
	  public void characters(char ch[], int start, int length)
	  	throws SAXException {

		  String tag = (String) ();
			if (("name")) {
			      ("name" + new String(ch, start, length));
			}
			if (("space")) {
			      ("space:" + new String(ch, start, length));
			}
}

	
	
	public static void main(String[] args) {
		//new XmlRead().TestDOM();
		new XmlRead().Dom4jReadTest();
		//new XmlRead().SAX();
	}
	
	

}


文件

<?xml version="1.0" encoding="UTF-8"?>
<list>
 <node>
  <name>
   weidewei
  </name>
  <space>
   
  </space>
 </node>
</list>


Sax解析xml

package ;

import ; 
import ; 

import ; 
import ; 
import ; 

import ; 
import ; 

public class PraseXML extends DefaultHandler 
{ 

  private Vector<String> tagName; 

  private Vector<String> tagValue; 

  private int step; 
  // 开始解析XML文件 
  public void startDocument() throws SAXException 
  { 
    tagName = new Vector<String>(); 
    tagValue = new Vector<String>(); 
    step = 0; 
  } 
  // 结束解析XML文件 
  public void endDocument() throws SAXException 
  { 
    for (int i = 0; i < (); i++) 
    { 
      if (!(i).equals("") || (i) != null) 
      { 
        ("节点名称:" + (i)); 
        ("节点值:" + (i)); 
      } 
    } 
  } 
  /** 
    * 在解释到一个开始元素时会调用此方法.但是当元素有重复时可以自己写算法来区分 
    * 这些重复的元素.qName是什么? <name:page ll=""></name:page>这样写就会抛出SAXException错误 
    * 通常情况下qName等于localName 
    */ 
  public void startElement(String uri, String localName, String qName, 
      Attributes attributes) throws SAXException 
  { 
    // 节点名称 
    (qName); 
    // 循环输出属性 
    for (int i = 0; i < (); i++) 
    { 
      // 获取属性名称 
      ("属性名称:" + (i)); 
      // 获取属性值 
      ("属性值:" 
          + ((i))); 
    } 

  } 

  /** 
    * 在遇到结束标签时调用此方法 
    */ 
  public void endElement(String uri, String localName, String qName) 
      throws SAXException 
  { 

    step = step + 1; 
  } 

  /** 
    * 读取标签里的值,ch用来存放某行的xml的字符数据,包括标签,初始大小是2048, 
    * 每解释到新的字符会把它添加到char[]里。    * 注意,这个char字符会自己管理存储的字符, 
    * 并不是每一行就会刷新一次char,start,length是由xml的元素数据确定的, 
    * 暂时找不到规律,以后看源代码. 
    *    
    * 这里一个正标签,反标签都会被执行一次characters,所以在反标签时不用获得其中的值 
    */ 
  public void characters(char ch[], int start, int length) 
      throws SAXException 
  { 
    // 只要当前的标签组的长度一至,值就不赋,则反标签不被计划在内 
    if (() - 1 == ()) 
    { 
      (new String(ch, start, length)); 
    } 
  } 

  public static void main(String[] args) 
  { 
    String filename = ""; 
    SAXParserFactory spf = (); 
    try 
    { 
      SAXParser saxParser = (); 
      (new File(filename), new PraseXML()); 
    } 
    catch (Exception e) 
    { 
      (); 
    } 
  } 
  public Vector getTagName() 
  { 
    return tagName; 
  } 
  public void setTagName(Vector tagName) 
  { 
     = tagName; 
  } 
  public Vector getTagValue() 
  { 
    return tagValue; 
  } 

  public void setTagValue(Vector tagValue) 
  { 
     = tagValue; 
  } 

} 


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

package ;

import ;  
import ;
import ;
import ;
import ;
import ;
import ;  
  
import ;  
import ;  
import ;
import ;  
import ;  
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
  
import org.;
import org.;
import org.;  
import org.;
import org.;  
import org.;
import org.;
import org.;  
import ;  
import ;  
import ;  

import ;
/**
 * 大体代码是从/topic/181865抄来的。
 * 下面这个是被广泛抄袭的,关于java里读取xml的概要介绍。
 * /geekwang/archive/2008/05/25/ 
 * 
 * 我主要是把从绝对路径读取xml换成了从classpath读取。
 * 另外添加了Transformer和xslt,以及XPath的演示,以及相关的一些链接。
 * 
 * 另外可以搜一下jaxp了解这个规范的相关内容。
 * 
 * @author YUQIAOTECH
 *
 */
public class SimpleSample  {  
  static String xmlName = "";
  static String xlst = "";
  static String dom4jSaveTo = "c:/";
  static String xsltSaveTo = "c:/";
  

    /** 
     * DOM方式 
     */  
    public void DOM() {  
        long lasting = ();  
  
        try {  
            InputStream in = (xmlName); 
            DocumentBuilderFactory factory = DocumentBuilderFactory  
                    .newInstance();
            DocumentBuilder builder = ();  
            Document doc = (in); //注意这里的Document是org.包下的
            NodeList nl = ("node");  
            for (int i = 0; i < (); i++) {  
                ("|| Name:  |"  
                        + ("name").item(i)  
                                .getFirstChild().getNodeValue());  
                ("||Space:  |"  
                        + ("space").item(i)  
                                .getFirstChild().getNodeValue());  
                ("-------------------------------------------------");            }  
        } catch (Exception e) {  
            ();  
        }  
        ("耗时:"  
                + (() - lasting) + " MS");  
    }  
  
    class SaxHandler extends DefaultHandler{
    	 tags = new ();  
        public void startElement(String uri, String localName, String qName,  
                Attributes attrs) {  
            (qName);  
        }  
      
        public void characters(char ch[], int start, int length)  
                throws SAXException {  
            String tag = (String) ();  
            if (("name")) {  
                ("|| Name:  |" + new String(ch, start, length));  
            }  
            if (("space")) {  
                ("||Space:  |" + new String(ch, start, length));  
            }  
            ("-------------------------------------------------");  
        }  
    }
  
    /** 
     * SAX方式 
     */  
    public void SAX() {  
  
        long lasting = ();  
        try {  
        	InputStream in = (xmlName); 
            SAXParserFactory sf = ();  
            SAXParser sp = ();  
            SaxHandler reader = new SaxHandler();  
            (in, reader);  
        } catch (Exception e) {  
            ();  
        }  
        ("SAX 耗时:"  
                + (() - lasting) + " MS");  
    }  
  

  
    /** 
     * 我懒得去了解JDOM了 :-)。
     * JDOM方式 
     */  
//    public void JDOM() {  
//        long lasting = ();  
//        try {  
//            SAXBuilder builder = new SAXBuilder();  
//             doc = (new File("F:/"));  
//            Element foo = ();  
//            List allChildren = ();  
//            for (int i = 0; i < (); i++) {  
//                ("|| Name:  |"  
//                        + ((Element) (i)).getChild("name")  
//                                .getText());  
//                ("||Space:  |"  
//                        + ((Element) (i)).getChild("space")  
//                                .getText());  
//                ("-------------------------------------------------");            }  
//        } catch (Exception e) {  
//            ();  
//        }  
//        ("JDOM RUNTIME:"  
//                + (() - lasting) + " MS");  
//    }  
  
    /** 
     * DOM4J方式 
     */  
    public void DOM4J() {  
        long lasting = ();  
        try {  
        	InputStream in = (xmlName); 
            SAXReader reader = new SAXReader();  
            org. doc = (in);  //注意这里的Document是org.dom4j包下的
            org. root = ();  
            org. foo;  
            for (Iterator i = ("node"); ();) {  
                foo = (org.) ();  
                ("|| Name:  |" + ("name"));  
                ("||Space:  |" + ("space"));  
                ("-------------------------------------------------");  
            }  
        } catch (Exception e) {  
            ();  
        }  
        ("DOM4J 耗时:"  
                + (() - lasting) + " MS");  
    }
    /**
     * 调用dom4j的保存方法。
     * 
     * @throws DocumentException
     * @throws IOException
     */
    public static void saveDocByDom4J() throws DocumentException, IOException{
        Writer out = new OutputStreamWriter(new FileOutputStream(dom4jSaveTo ),"GBK");
        OutputFormat format = ();
        XMLWriter writer = new XMLWriter( out, format );
    	InputStream in = (xmlName); 
        SAXReader reader = new SAXReader();  
        org. doc = (in);  
        ( doc );
        ();
    }

    /**
     * 使用Transformer和xslt。
     * /developerworks/cn/xml/x-xslt/
     * 
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
	public static void saveByTransformer() throws ParserConfigurationException, SAXException, IOException {
		try {
			InputStream in = (xmlName); 
			InputStream inXsl = (xlst); 
	        DocumentBuilderFactory factory = DocumentBuilderFactory  
	                .newInstance();  
	        DocumentBuilder builder = ();  
	        Document doc = (in); 
	        StreamSource style = new StreamSource(inXsl); 
			TransformerFactory tFactory = ();
			Transformer transformer = (style);
			(, "GBK");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(xsltSaveTo));
			(source, result);
		} catch (TransformerConfigurationException e) {
			throw new RuntimeException((), e);
		} catch (TransformerException e) {
			throw new RuntimeException((), e);
		}
	}
	
	//**********************XPath*****************************
	
	/**
	 * 返回指定的节点。
	 * 
	 * @param topNode
	 * @param xPath
	 * @return
	 */
	public static Node selectSingleNode(Node topNode, String xPath) {
		try {
			return (topNode, xPath);
		} catch (TransformerException e) {
			(() + " xPath=" + xPath);
			throw new RuntimeException((), e);
		}
	}

	/**
	 * 根据属性名获取属性节点。
	 * 
	 * @param node
	 * @param attributeName
	 * @return
	 */
	public static Node getAttributeNode(Node node, String attributeName) {
		NamedNodeMap namedNodeMap = ();
		return (attributeName);
	}

	/**
	 * 几个方法的组合。
	 * 
	 * @param node
	 * @param xPath
	 * @param attributeName
	 * @return
	 */
	public static String getAttributeNodeByXPath(Node node, String xPath,
			String attributeName) {
		Node rtn = null;
		Node selectedNode = selectSingleNode(node, xPath);
		if (selectedNode != null) {
			rtn = getAttributeNode(selectedNode, attributeName);
		}
		if(rtn == null)return null;
		return ();
	}
	/**
	 * /xxl/XPathTutorial/General_chi/
	 * /developerworks/cn/xml/
	 * 
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static void XPath() throws ParserConfigurationException, SAXException, IOException{
		InputStream in = (xmlName); 
        DocumentBuilderFactory factory = DocumentBuilderFactory  
                .newInstance();  
        DocumentBuilder builder = ();  
        Document doc = (in); 
        String attr = getAttributeNodeByXPath(doc,"//node[@id=1]/name","alias");
        ("alias="+attr);
        
	}
    public static void main(String arge[]) throws ParserConfigurationException, SAXException, IOException, DocumentException {  
        SimpleSample myXML = new SimpleSample();  
        ("=====================DOM=========================");  
        ();  
        ("=====================SAX=========================");  
        ();  
        //("=====================JDOM========================");  
        //();  
        ("=====================DOM4J=======================");  
        myXML.DOM4J();  
        ("=====================DOM4J的格式化保存=======================");   
        saveDocByDom4J();
        ("=====================Transformer和xslt的使用=======================");  
        saveByTransformer();
        ("=====================XPath的演示======================="); 
        XPath();
    }  
}  


<?xml version="1.0" encoding="gbk"?>
<list>
 <node ><name alias="李逵">张三</name><space></space></node>
 <node><name>李四</name><space>/94611981</space></node>
</list>  


<xsl:transform
xmlns:xsl="http:///1999/XSL/Transform"
version="1.0">
<xsl:variable name="nodes" select="//node"/>
<xsl:template match="list">
<html><body>
 <h1>名单</h1>
 <table cellpadding="5">
 <tr>
 <td>姓名</td>
 <td>博客</td>
 </tr>
 <xsl:for-each select="$nodes">
 <tr>
 <td> <xsl:value-of select="./name"/>(<xsl:value-of select="./name/@alias"/>)</td>
 <td> <xsl:value-of select="./space"/></td>
 </tr>
 </xsl:for-each>
 </table>
</body></html>
</xsl:template>
</xsl:transform>