XML 操作


public class XMLUtil {

	private static final String ENCODE= "GBK" ;
	private static String BOLG_PATH = ConfigLocation.getWebRoot().concat("xmlFile/bolg.xml");

	public static void updateNode(String filePath ,Document doc){
		XMLWriter writer = null ;
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding(ENCODE);
			writer = new XMLWriter(new FileWriter(filePath), format);
			writer.write(doc);
		} catch (Exception e) {
			e.printStackTrace() ;
			throw new RuntimeException(filePath + "SAVE FAILED ") ;
		}finally{
			try {
				if(writer!=null)
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Document getDocument(String filePath){
		SAXReader sax  = new SAXReader() ;
		Document doc  = null;
		File f  =  null ;
		try {
			 f = new File(filePath);
			 doc = sax.read(f) ;
		} catch (DocumentException e) {
			throw new RuntimeException(filePath + " NOT FOUND") ;
		}
		return doc;
	}


/*   XML文件结构	
<bolg> 
  <link_bolg>http://t.sina.com.cn/?c=spr_web_sq_baidub_weibo_t001</link_bolg>  
  <link_readBook></link_readBook> 
  <periodicals></periodicals>
</bolg>
*/

 //查询link_bolg
  public static String search(){
	Element bolg  = (Element) XMLUtil.getDocument(BOLG_PATH).selectSingleNode("//link_bolg");
			if(bolg!=null){
				return bolg.getText() ;
			}
			return "";
  }

 //修改link_bolg
public static void modifBolg(String link){
	Document doc  = XMLUtil.getDocument(BOLG_PATH) ;
	Element bolg  = (Element) doc.selectSingleNode("//link_bolg");
	bolg.setText(link);
	XMLUtil.updateNode(BOLG_PATH, doc);
}

 //删除
 public static void delLinkBolg(){
	    Document doc  = XMLUtil.getDocument(BOLG_PATH) ;
		Element bolg  = (Element) doc.selectSingleNode("//link_bolg");
		bolg.getParent().remove(bolg) ;
		XMLUtil.updateNode(BOLG_PATH, doc);
 }

 //新增一个新节点
 public static void addNode(){
	 Document doc  = XMLUtil.getDocument(BOLG_PATH) ;
	 Element ele = doc.addElement("newNode");
			 ele.setText("这是新节点");		
	XMLUtil.updateNode(BOLG_PATH, doc);
 }

}

你可能感兴趣的:(xml,F#)