java 對 XML 字符, XML文件的解釋

java解釋與讀取XML文件 或者是XML字符串, 有多種方法,

對於內容比較小的XML 採用 Document 方式比較方便

以下就是完整的XML讀取解釋代碼:

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.ParameterMode;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

/**
 * 調用服務例子DOM方式解釋
 * 1 生成XML字符串方法
 * 2 調用服務方法 axis1
 * 3 解釋數據方法
 * 4 DOM,文件,String之間的換方法
 */
public class WebServiceCodeDemo2 {
	
	/**
	 * 取得DOC對象中的數據,轉成對象.
	 * @date 2008-3-10
	 * @param strXml
	 * @return
	 */
	private List<Object[]> processEntityXml(Document doc){
		List<Object[]> list = new ArrayList<Object[]>();
		NodeList nodeRows = doc.getElementsByTagName("ROW");
		String xmlData= null;
		Date dateTime= null;
		Object[] dto = null;
		SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (nodeRows != null && nodeRows.getLength() > 0) {
			for (int i = 0; i < nodeRows.getLength(); i++){
				dto = new Object[3];
				Element rowE = (Element) nodeRows.item(i);
				//實體
				dto[0]=getNodeValueByName(rowE,"OBJ");
				dto[1]=getNodeValueByName(rowE,"SID");
				if(dateTime==null){
					xmlData = getNodeValueByName(rowE,"DT");
					try {
						dateTime = dateFromat.parse(xmlData);
					} catch (ParseException e) {
						throw new RuntimeException("時間數據錯誤");
					}
					dto[2]=dateTime;
				}else{
					dto[2]=dateTime;
				}
				if (dto[1]== null) {
					throw new RuntimeException(",對象編號不能爲空");
				}
				if (dto[2]==null){
					throw new RuntimeException(",時間數據錯誤(格式:2009-01-01 08:00:00)");
				}
				list.add(dto);
				if(i>200){
					throw new RuntimeException(",參數個數最多不能超過200,請限制數量.");
				}
			}
		} else {
			throw new RuntimeException("解釋XML時沒有找到數據");
		}
		nodeRows = null;
		xmlData=null;
		dto = null;
		System.out.println(",解釋出XML參數有效的數據行數: " + list.size());
		return list;
	}
	
	/**
	 * 把對象轉成XML
	 */
	private String processEntity(List<Object[]> entitys){
		String returnStr = null;
	    String sRootName = "RESULT";
	    Document doc = new DocumentImpl();
    	Element root = doc.createElement(sRootName);
    	doc.appendChild(root);
    	Element rows = doc.createElement("ROWS");
    	rows.setAttribute("ID", "張三");
    	root.appendChild(rows);
	    if (entitys != null && entitys.size() > 0) {
	    	Element edata =null;
	    	Integer id = -1;
	    	try{
	    		Object[]  e =null;
	    		for(int i=0; i<entitys.size(); i++){
	    			e =entitys.get(i);
	    			id =(Integer)e[0];
	            	edata = doc.createElement("ROW");
	            	addDocElement(doc, edata, "OBJ", "USER001");
	            	addDocElement(doc, edata, "SID", id.toString());
			   		addDocElement(doc, edata, "DT", "2014-02-02 00:00:00");
			   		
			   		addDocElement(doc, edata, "PP0", "100.00");
			   		addDocElement(doc, edata, "NP0", "100.00");
			   		addDocElement(doc, edata, "PQ0", "100.00");
			   		addDocElement(doc, edata, "NQ0", "100.00");
			   		rows.appendChild(edata);
	            }
	    		//總行數
	    		addDocElement(doc, rows, "RECORDCOUNT", String.valueOf(entitys.size()));
			   	returnStr = docToXML(doc);
	    	}catch (Exception ex) {
	    		ex.printStackTrace();
	    		returnStr= this.processErrorXml("把數據轉換XML發生內部錯誤");
	    	}finally {
	    		edata =null;
	    	}
	    }else{
	    	returnStr= this.processErrorXml("沒有數據");
	    }
	    root= null;
	    doc = null;
	    return returnStr;
	}
	
	/** 生成錯誤的XML */
	private String processErrorXml(String info){
		String xml="<?xml version=\"1.0\" encoding=\"gb2312\" ?>" 
			+"<RESULT><RECORDCOUNT>0</RECORDCOUNT><DM>-1</DM><MC>"+info+"</MC></RESULT>";
		return xml;
	}
	
	/**
	 * 
	 * 向doc文檔添加新文本元素,不要用此方法添加非文本元素.<br>
	 * 若元素值爲null,則文檔值設置爲空""字符.
	 * @param document 文檔
	 * @param parent 父節點
	 * @param elementName 文本元素名
	 * @param elementValue 文本元素值
	 * @return 無
	 */
	public void addDocElement(Document document,Element parent,String elementName,String elementValue) {
		Element e = document.createElement(elementName);
		parent.appendChild(e);
	    Text te = elementValue!= null ? document.createTextNode(elementValue)
	    		: document.createTextNode("");
	    e.appendChild(te);
	    e = null;
	    te= null;
	}
	/**
     * 根據名稱從節點中獲得值
     * @param rowE Element 行節點
     * @param sName String 列名稱
     * @return String
     */
    public static String getNodeValueByName(Element rowE, String sName) {
        String nodeValue = null;
        Node rowdeviceType1 = rowE.getElementsByTagName(sName).item(0);
        if (rowdeviceType1 != null) {
            Node rowdeviceType = rowdeviceType1.getFirstChild();
            if (rowdeviceType != null) {
                nodeValue = (String) rowdeviceType.getNodeValue().trim();
            }
        }
        rowdeviceType1=null;
        return nodeValue;

    }
	
	/**
	 * 把doc轉換成字符串的 普通轉換
	 * (此方法不能格式,設置字符編碼)
	 * @param doc
	 * @return
	 */
	public String getStringByDocument(Document doc){
		String xmlString =null;
		try {
	        //把dom轉成XML file或string
	        DOMSource domIn = new DOMSource(doc);
	        StringWriter stringOut = new StringWriter();
	        StreamResult StreamOut = new StreamResult(stringOut);
	        TransformerFactory tff = TransformerFactory.newInstance();
	        Transformer  ft = tff.newTransformer();
	        ft.transform(domIn, StreamOut);
	        xmlString = stringOut.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		//System.out.println(xmlString);
		return xmlString;
	}

	/**
	 * 把文檔轉成XML字符串,並且格式化數據,設置編碼格式
	 * @param doc 內容文檔
	 * @return
	 */
	public static String docToXML(Document doc) {
		StringWriter stringOut;
		XMLSerializer serial;
		OutputFormat format = new OutputFormat(doc, "GB2312", true);
		stringOut = new StringWriter();
		serial = new XMLSerializer(stringOut, format);
		try {
			serial.asDOMSerializer();
			serial.serialize(doc.getDocumentElement());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println(stringOut.toString());
		return stringOut.toString();
	}

	/**
	 * 把XML文件轉換成字符串的 普通轉換
	 * @param doc
	 * @return
	 */
	public String getStringByFile(String sFileName){
		String xmlString =null;
		try {
	        Document dom = this.getDocumentByFile(sFileName);
	        xmlString = this.getStringByDocument(dom);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		//System.out.println(xmlString);
		return xmlString;
	}
	

	/**
	 * 把XML文件轉換成Document
	 * @param doc
	 * @return
	 */
	public Document getDocumentByFile(String sFileName){
		Document dom =null;
		try {
			//文件流
			//String sFileName ="D:/testData/XML123.xml";
			File file = new java.io.File(sFileName);
			FileInputStream fis = new java.io.FileInputStream(file);
			//把xml file 轉成dom
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
	        dom = builder.parse(fis);
	        //
	        factory =null;
	        fis.close();
	        fis =null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		return dom;
	}
	

	/**
	 * 把XML字符串轉換成Document
	 * @param doc
	 * @return
	 */
	public Document getDocumentByString(String xmlString){
		Document dom =null;
		try {
			//把xml string 轉成dom
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
	        InputSource is = new InputSource(new StringReader(xmlString)); 
	        dom = builder.parse(is);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return dom;
	}
	
	
	
	public static void main(String[] args) {
		Date dateFrom =null;
		List<Object[]> entitys = new ArrayList<Object[]>();
		Object[] aa =new Object[]{10000,2};
		entitys.add(aa);//1
		aa =new Object[]{10001,3};
		entitys.add(aa);//2
		//測試
		WebServiceCodeDemo2 bb = new WebServiceCodeDemo2();
		String xml =bb.processEntity(entitys);
		System.out.println("調用結果: "+xml);
		
		//工具測試
		Document dom=bb.getDocumentByString(xml);
		xml = bb.getStringByDocument(dom);
		System.out.println("工具測試2: "+xml);
		//
		dom =bb.getDocumentByFile("D:/testData/GetCode.xml");
		xml = bb.getStringByDocument(dom);
		System.out.println("工具測試1: "+xml);
		
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章