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);
}
}