首页>代码>dom4j操作xml文件读取插入的实例>/Querydrug/src/cn/datasource/xml/AddDrug.java
package cn.datasource.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class AddDrug {
	public static void addUser(Map<String,String> drug){
		try{
		  //读取文件
		  SAXReader saxReader = new SAXReader();
		  Document doc = saxReader.read(new File(Constant.DRUGFILEPATH));
		  //得到跟结点root
		  Element root = doc.getRootElement();
		  //往根节点添加drug元素
		  Element Drug = root.addElement("drug");
		  //设置drug的drugID
		  Drug.addAttribute("drugID", drug.get("code").toString());
		  //往user添加各种子元素和设置值
		  Element code = Drug.addElement("code");
		  code.setText(drug.get("code").toString());
		  Element name = Drug.addElement("name");
		  name.setText(drug.get("name").toString());
		  Element pill = Drug.addElement("pill");
		  pill.setText(drug.get("pill").toString());
		  Element type = Drug.addElement("type");
		  type.setText(drug.get("type").toString());
		  Element grade = Drug.addElement("grade");
		  grade.setText(drug.get("grade").toString());
		  //添加元素结束后往新的文件重新写入doc数据
		  XMLWriter output = new XMLWriter(new FileWriter( new File(Constant.DRUGFILEPATH) ));
		  output.write(doc);
		  //关闭输出流
		  output.close();
		}catch(DocumentException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Map<String,String> drugMap = new HashMap<String,String>();
		drugMap.put("code", "X-J05AF-A014-A006");
		drugMap.put("name", "阿德福韦酯");
		drugMap.put("pill", "分散片");
		drugMap.put("type", "西药");
		drugMap.put("grade", "乙");
		
		AddDrug.addUser(drugMap);
	}
}
最近下载更多
我是helloworld  LV23 2023年6月12日
chokkint  LV12 2021年10月29日
kld113  LV20 2019年3月5日
07311514  LV9 2019年2月22日
爱情的本质  LV15 2019年2月10日
murphyLu  LV12 2019年1月4日
wyx065747  LV67 2018年12月2日
最代码官方  LV167 2018年11月30日
最近浏览更多
sipm123  LV1 2023年3月5日
xiaoding1999  LV7 2022年4月1日
chokkint  LV12 2021年10月29日
yuzhiyuan1977  LV2 2021年8月2日
15939671505 2020年12月18日
暂无贡献等级
pxqtsht  LV15 2020年11月12日
1234567891011  LV5 2020年6月27日
加油干阳神  LV8 2020年5月13日
3969138  LV15 2020年1月15日
为伊消得  LV1 2019年8月9日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友