日期:2014-05-17 浏览次数:20874 次
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class XmlTest { /** * @author butnet * @param args * @throws DocumentException */ public static void main(String[] args) throws DocumentException { Document doc = DocumentHelper.parseText("<user><name>butnet</name><web>http://jvmer.com</web></user>"); Element user = doc.getRootElement(); Element name = user.element("name"); Element web = user.element("web"); System.out.println(name.getText()); System.out.println(web.getText()); } } /*使用DOM4J可以很方便的对XML进行读写, 项目地址 http://dom4j.sourceforge.net/ */
------解决方案--------------------
package com.anxin.dod;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.anxin.beans.*;
public class Login {
public static String saveXmlFilePath;
T_yonghu c=new T_yonghu();
//SAXReader reader=new SAXReader();//构建sax读取对象
List<T_yonghu> list = new ArrayList<T_yonghu>();
public T_yonghu readXML(String yhmc,String yhma,String path) throws IOException{
Document doc=(Document) Login.getXmlDocument(path);
Element ele=doc.getRootElement();
List eles=ele.elements("用户");
//System.out.println("根节点:"+ele.getName());
//Iterator it=root.elementIterator();//获取根节点下面的所有子节点
for(Iterator childs=eles.iterator();childs.hasNext();){
Element el = (Element)childs.next();
//System.out.println("yonghu:"+el.getText());
// System.out.println("yonghu:"+el.attributeValue("用户密码"));
if(yhmc.equals(el.getText()) && yhma.equals(el.attributeValue("用户密码")))
{ c.setYhmc(el.getText());
//c.setYhma(el.element("用户名称").attributeValue("用户密码"));
c.setYhsf(el.attributeValue("用户身份"));
c.setId(el.attributeValue("id"));
//list.add(c);
}
}
return c;
}
public static Document getXmlDocument(String saveXmlFilePath){
setSaveXmlFilePath(saveXmlFilePath);
SAXReader reader = new SAXReader();
Document doc = null;
try {
doc = reader.read(new File(saveXmlFilePath));
}finally{
return doc;
}
}
public static void saveDocument(Document doc) throws IOException{
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileOutputStream(saveXmlFilePath),format);
writer.write(doc);
writer.close();
}
public static String getSaveXmlFilePath() {
return saveXmlFilePath;
}
public static void setSaveXmlFilePath(String saveXmlFilePath) {