这次搞个基金的信息fund.xml放在工程根目录下:
<?xml version="1.0" encoding="utf-8" ?>
<funds>
<fund ID="0">
<name>华夏大盘</name>
<code>000011</code>
<type>混合型</type>
<url>http://jingzhi.funds.hexun.com/000011.shtml</url>
</fund>
<fund ID="1">
<name>华安宏利</name>
<code>040005</code>
<type>股票型</type>
<url>http://jingzhi.funds.hexun.com/040005.shtml</url>
</fund>
</funds>
ID还是大写字母的"ID"作attribute。
构造个相应的Java Bean:
package leon.corejava.model;
public class Fund {
private String name;
private String code;
private String url;
private String type;
public String toString(){
return this.code+"\t"+this.name+"\t"+this.url;
}
//getter and setter
//...
}
测试类:
package leon.corejava.xml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import leon.corejava.model.Fund;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class FundXMLTest {
public static final String ID="ID";
public static void main(String[] args) throws Exception {
File xmlFile = new File("fund.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(xmlFile);
Element root = doc.getRootElement();
List<Fund> fundList = new ArrayList<Fund>();
int i=0;
for(Iterator iter = root.elementIterator();iter.hasNext();){
Element element = (Element) iter.next();
fundList.add(elementToFund(element));
i++;
}
for(Fund f : fundList){
System.out.println(f);
}
//modify element
Element e = root.elementByID("0");
e.element("name").setText("华夏大盘精选");
//add new element
Element newFund = root.addElement("fund");
newFund.addAttribute(ID, String.valueOf(i));
newFund.addElement("name").setText("中信双利");
newFund.addElement("code").setText("288102");
newFund.addElement("url").setText("http://jingzhi.funds.hexun.com/288102.shtml");
write(doc,new File("new_fund.xml"));
}
public static Fund elementToFund(Element e){
Fund f = new Fund();
f.setCode(e.element("code").getTextTrim());
f.setName(e.element("name").getTextTrim());
f.setUrl(e.element("url").getTextTrim());
f.setType(e.element("type").getTextTrim());
return f;
}
public static void write(Document document,File f) throws IOException {
// format xml
OutputFormat format = OutputFormat.createPrettyPrint();
// format short xml
//format = OutputFormat.createCompactFormat();
//not format
//XMLWriter writer = new XMLWriter(new FileWriter(f));
//format.setEncoding("GBK");
//format
XMLWriter writer = new XMLWriter(new FileWriter(f),format);
writer.write(document);
/*
// format short xml
format = OutputFormat.createCompactFormat();
writer = new XMLWriter(System.out, format);
*/
writer.close();
}
}
工程根目录创建出一个新的文件new_fund.xml。