XML读写操作

前端之家收集整理的这篇文章主要介绍了XML读写操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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();  
    }  
}
原文链接:https://www.f2er.com/xml/299490.html

猜你在找的XML相关文章