java怎么读写xml文件 20
java本身好像不自带吧?
大家都用哪些jar包?
我以前用过dom4j
不过找了半天 只会从xml读取数据
不会把数据写回xml
求大神帮忙 展开
谁说不自带的rt.jar就是啊
1.接口
/**
*
*/
package com.huawei.liyong.interfaces;
import java.util.Map;
/**
* @author Administrator
*/
public interface OperateTool
{
/**
* 解析XML
*/
Map<String, String> parseXML( String xmlPath, String root );
/**
* 写入文件
*/
void writeToFile( String filePath, String content );
/**
* 排序
*/
void orderScore( Map<String, String> map, String resultPath );
}
2.实体Bean 学生
/*
* 文件名: Student.java
* 版权: 〈版权〉
* 描述: 〈描述〉
* 撰写人: Administrator
* 修改时间: Jul 31, 2011
* 跟踪单号:〈跟踪单号〉
* 修改单号:〈修改单号〉
* 修改内容:〈修改内容〉
*/
package com.huawei.liyong.bean;
/**
* <P>
* Description: //描述类的信息和作用
*
* @author Administrator
*/
public class Student
{
private String name;
private String place;
private String score;
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name
* the name to set
*/
public void setName( String name )
{
this.name = name;
}
/**
* @return the place
*/
public String getPlace()
{
return place;
}
/**
* @param place
* the place to set
*/
public void setPlace( String place )
{
this.place = place;
}
/**
* @return the score
*/
public String getScore()
{
return score;
}
/**
* @param score
* the score to set
*/
public void setScore( String score )
{
this.score = score;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return new StringBuffer().append(
Student.class.getName()
+ "[name="
+ this.name
+ ",place="
+ this.place
+ ",score="
+ this.score
+ "]").toString();
}
}
3.具体操作类
/**
*
*/
package com.huawei.liyong.action;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.huawei.liyong.bean.Student;
import com.huawei.liyong.interfaces.OperateTool;
/**
* @author Administrator
*/
public class OperaterAction
{
/**
* @param args
*/
public static void main( String[] args )
{
Operator o = new Operator();
o.orderScore(o.parseXML("student.xml", "student"), "result.txt");
}
}
class Operator implements OperateTool
{
private DocumentBuilderFactory dbf;
private DocumentBuilder db;
private Document document;
private NodeList nodeList;
private Map<String, String> map = new HashMap<String, String>();
private Student student = new Student();
public Map<String, String> parseXML( String xmlPath, String root )
{
// TODO parseXML
try
{
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
document = db.parse(xmlPath);
nodeList = document.getElementsByTagName(root);
for( int j = 0; j < nodeList.getLength(); j++ )
{
map.put("all" + j, nodeList.item(j).getChildNodes().item(1)
.getTextContent()
+ ","
+ nodeList.item(j).getChildNodes().item(3)
.getTextContent()
+ ","
+ nodeList.item(j).getChildNodes().item(5)
.getTextContent());
}
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return map;
}
public void writeToFile( String filePath, String content )
{
FileWriter fw = null;
File f = null;
try
{
f = new File(filePath);
fw = new FileWriter(f);
fw.write(content);
fw.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(null != fw)
{
fw.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public void orderScore( Map<String, String> maps, String resultPath )
{
String[] array = null;
StringBuffer buffer = new StringBuffer();
StringBuffer sbf = new StringBuffer();
String temp = "";
for( int i = 0; i < maps.size(); i++ )
{
buffer.append(maps.get("all" + i) + ";");
}
array = buffer.toString().split(";");
for( int i = 0; i < array.length; i++ )
{
for( int j = i; j < array.length; j++ )
{
if(Integer.parseInt(array[i].substring(array[i]
.lastIndexOf(",") + 1, array[i].length())) < Integer
.parseInt(array[j].substring(array[j].lastIndexOf(",") + 1,
array[j].length())))
{
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
for( int i = 0; i < array.length; i++ )
{
student.setName(array[i].split(",")[0]);
student.setPlace(array[i].split(",")[1]);
student.setScore(array[i].split(",")[2]);
sbf.append(student.toString() + "\n");
writeToFile(resultPath, sbf.toString());
}
}
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
/**
* xml 工具类 先调用init(),后边使用xpath获取element内容
*
* @author changlei
*
*/
public class CommonXMLUtil {
protected SAXBuilder builder;
protected Document document;
public CommonXMLUtil() {
super();
}
/**
* 初始化
*
* @param xmlStr
* @throws JDOMException
* @throws IOException
*/
public void init(String xmlStr) throws JDOMException, IOException {
builder = new SAXBuilder();
ByteArrayInputStream ins = null;
ins = new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
document = builder.build(ins);
}
/**
* 初始化
*
* @param xmlStr
* @throws JDOMException
* @throws IOException
*/
public void init(String xmlStr,String encode) throws JDOMException, IOException {
builder = new SAXBuilder();
ByteArrayInputStream ins = null;
ins = new ByteArrayInputStream(xmlStr.getBytes(encode));
document = builder.build(ins);
}
/**
* 获取element的值
*
* @param xpath
* @return
* @throws JDOMException
*/
public String getElementValue(String xpath) throws JDOMException {
String val = null;
Element element = (Element) XPath.selectSingleNode(
document.getRootElement(), xpath);
if (element != null) {
val = element.getValue();
}
return val;
}
/**
* 获取element attribute的值
*
* @param xpath
* @return
* @throws JDOMException
*/
public String getAttrValue(String elementXpath,String attrName) throws JDOMException {
String val = null;
Element element = (Element) XPath.selectSingleNode(
document.getRootElement(), elementXpath);
if (element != null) {
val = element.getAttributeValue(attrName);
}
return val;
}
}
调用范例
CommonXMLUtil xmlUtil = new CommonXMLUtil();
xmlUtil.init(messageBody, "GBK");
// 根据响应码解析交易结果
String retCode = xmlUtil
.getElementValue("/BOSEBankData/opRep/retCode");
String retMsg = xmlUtil
.getElementValue("/BOSEBankData/opRep/errMsg");
String orgOrderNo = xmlUtil
.getElementValue("/BOSEBankData/opRep/serialNo");
2015-12-05 · 做真实的自己 用良心做教育
List<Student> empvoList = new ArrayList<Student>();
File file = new File(path);
//输入流对象
FileInputStream fis = new FileInputStream(file);
//jdom解析器
SAXBuilder sb = new SAXBuilder();
Document doc= sb.build(fis);
//获得XML的根元素
Element root = doc.getRootElement();
//获得根元素下的所有子元素
List<Element> employees = root.getChildren();
for(int i=0;i<employees.size();i++){
Element employee =employees.get(i);
Student stu= new Student();
String name = employee.getChildText("name");
String sex = employee.getChildText("sex");
String agetemp = employee.getChildText("age");
String home = employee.getChildText("home");
String email = employee.getChildText("email");
stu.setName(name);
stu.setSex(sex);
int age = 0;
if(agetemp.equals("")){
age = 0;
} else {
age = Integer.parseInt(agetemp);
}
stu.setAge(age);
stu.setHome(home);
stu.setEmail(email);
System.out.println(name+"\t"+i);
empvoList.add(stu);
}
return empvoList;
}