加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML读写操作

发布时间:2020-12-16 05:12:40 所属栏目:百科 来源:网络整理
导读:public class ParseXML {//解析XML文件 public MapString,String loadXML(String filename){ SAXReader saxReader = new SAXReader(); MapString,String bean = new HashMap(); try { Document document = saxReader.read(new File(filename)); // 获取根结
public class ParseXML {
	//解析XML文件
   public Map<String,String> loadXML(String filename){
 	   SAXReader saxReader = new SAXReader();
 	   Map<String,String> bean = new HashMap<>();
 		try {
 			Document document = saxReader.read(new File(filename));
 			// 获取根结点
 			Element root = document.getRootElement();
 			// 遍历根结点的所有孩子节点
 			for (Iterator iter = root.elementIterator(); iter.hasNext();) {
 				Element element = (Element) iter.next();
 				Attribute aliasAttr = element.attribute("alias");
 				String aliasName = aliasAttr.getValue();
 				Attribute fileAttr = element.attribute("file");
 				String fileName = fileAttr.getValue();
 				//原字符串res/CC/CC06_00_265_00.xml,输血反应类型字典
 				//拼装字符串生成需要的格式字符串,CC06_00_265_00.xml,输血反应类型字典
 				int lastIndex = fileName.lastIndexOf("/");
 				fileName = fileName.substring(lastIndex+1);
 				bean.put(fileName,aliasName);
 			}
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 		return bean;
 		}
   
   //向XML中添加内容
   public void writeXMl(String xmlPath,String content){
    try{
	    SAXReader reader = new SAXReader();  
	    Document document = reader.read(new File(xmlPath));
		Element root = document.getRootElement();
		root.addAttribute("alias",content);  
		writerXMLDocument(document,xmlPath);
	} catch (DocumentException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}  
   }
   
   //将内存中的xml写回硬盘XML文件
   public void writerXMLDocument(Document document,String fileName) throws IOException  
    {  
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(fileName),OutputFormat.createPrettyPrint());  
        xmlWriter.write(document);  
        xmlWriter.flush();
        xmlWriter.close();  
    }  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读