当前位置: 代码迷 >> XML/SOAP >> java写xml 以及 向xml累加节点内容
  详细解决方案

java写xml 以及 向xml累加节点内容

热度:1861   发布时间:2014-01-05 18:22:55.0
java写xml 以及 向xml追加节点内容

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.dom4j.DocumentHelper;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.w3c.dom.UserDataHandler;


// 将用户要增加的倾向性分析数据增加至XML文件
	private static void updateSentimentFile(String title, String text, String lable,long time) throws Exception {
		String filePath = util.Constants.SENTIMENT_FILE_PATH;//获取配置的倾向性目录
		// 上传后实际保存在服务器上的文件名: 
		String saveName = "sentiment_" + time + "_" + XString.random(8) + ".xml";//"_" + System.currentTimeMillis() + "_" + XString.random(8) + "_" + uploaded.getName();
		title = title.replaceAll("<", " ").replaceAll(">", " ");//过滤xml敏感符号  < 和 > 
		text = text.replaceAll("<", " ").replaceAll(">", " ");//过滤xml敏感符号  < 和 > 
		// 创建保存目录
		File toSave = new File(filePath + "a/");
		if (!toSave.exists()) {
			toSave.mkdirs();
		}
		// 保存文件
		toSave = new File(filePath + "a/" + saveName);
		File checkFile = new File(filePath + "b/check.txt");
		if(checkFile.exists()){//删除校验文件
			play.libs.Files.delete(checkFile);
		}
		createXML(title, text, lable, time, toSave);//写入添加的文件到A目录
		File bFile = new File(filePath + "b/");
		if (!bFile.exists()) {
			bFile.mkdirs();
		}
		bFile = new File(filePath + "b/sentiment.xml");
		if (!bFile.exists()) {
			play.libs.Files.copy(toSave, bFile);//B目录没有XML的情况下将A目录的XML写入B目录
		}else{
			writeXML(title, text, lable, time, bFile, toSave);//B目录存在XML的情况下 向B目录的XML增加写入传来的内容
		}
		
		checkFile.createNewFile();//重新创建校验文件
	}



//向xml追加节点内容
	private static void writeXML(String title, String text, String lable, long time, File bFile, File aFile) throws Exception{
		/*Document docs = null;
		try {
			docs = play.libs.XML.getDocument(bFile);
		} catch (Exception e) {
			play.libs.Files.delete(bFile);
			play.libs.Files.copy(aFile, bFile);
			return;
		}*/
		 // 1.得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 2.从DOM工厂里获取DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        // 3.解析XML文档,得到DOM树
        Document docs = null;
		try {
			docs = db.parse(bFile);
		} catch (Exception e) {
			play.libs.Files.delete(bFile);
			play.libs.Files.copy(aFile, bFile);
			return;
		}
		//创建节点
		Element docElement = docs.createElement("doc");
		Element lableElement =  docs.createElement("lable");
		Text l = docs.createTextNode(lable);
		lableElement.appendChild(l);//lableElement.setNodeValue(lable);
		Element titleElement =  docs.createElement("title");
		Text t = docs.createTextNode(title);
		titleElement.appendChild(t);//titleElement.setNodeValue(title);
		Element textElement =  docs.createElement("text");
		Text x = docs.createTextNode(text);
		textElement.appendChild(x);//textElement.setNodeValue(text);
		Element timeElement =  docs.createElement("timemillis");
		Text m = docs.createTextNode(time + "");
		timeElement.appendChild(m);
		
		//添加父子关系
		docElement.appendChild(lableElement);
		docElement.appendChild(titleElement);
		docElement.appendChild(textElement);
		docElement.appendChild(timeElement);
		//Element docsElement=(Element)docs.getElementsByTagName("docs").item(0);
		//docsElement.appendChild(docElement);
		docs.getDocumentElement().appendChild(docElement);
		
		//保存xml文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(docs);
        
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        StreamResult result=new StreamResult(new FileOutputStream(bFile));
        
        //把DOM树转换为xml文件
        transformer.transform(domSource, result);
	}
	
	//新建xml文件写入内容
	private static void createXML(String title, String text, String lable, long time, File bFile) throws Exception{
		 // 1.得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 2.从DOM工厂里获取DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        // 3.创建document,即DOM树
        Document docs = db.newDocument();
		
		//创建根节点
        Element docsElement = docs.createElement("docs");
        docs.appendChild(docsElement);
        //创建子节点
		Element docElement = docs.createElement("doc");
		Element lableElement =  docs.createElement("lable");
		Text l = docs.createTextNode(lable);
		lableElement.appendChild(l);//lableElement.setNodeValue(lable);
		Element titleElement =  docs.createElement("title");
		Text t = docs.createTextNode(title);
		titleElement.appendChild(t);//titleElement.setNodeValue(title);
		Element textElement =  docs.createElement("text");
		Text x = docs.createTextNode(text);
		textElement.appendChild(x);//textElement.setNodeValue(text);
		Element timeElement =  docs.createElement("timemillis");
		Text m = docs.createTextNode(time + "");
		timeElement.appendChild(m);//timeElement.setNodeValue(time + "");
		
		//添加父子关系
		docElement.appendChild(lableElement);
		docElement.appendChild(titleElement);
		docElement.appendChild(textElement);
		docElement.appendChild(timeElement);
		docsElement.appendChild(docElement);
		
		//保存xml文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(docs);
        
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        StreamResult result=new StreamResult(new FileOutputStream(bFile));
        
        //把DOM树转换为xml文件
        transformer.transform(domSource, result);
	}

  相关解决方案