dom4 jxml插入
package com.huawei.test;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
public class InsertElement {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
SAXReader reader = new SAXReader();
Document document = reader.read("C:\\Users\\Administrator\\Desktop\\strings.xml");
Element root = document.getRootElement();
List<Element> elements = root.elements();
int index = 0;
for(Element element:elements){
index++;
if("app_name".equals(element.attributeValue("name"))){
Element elem = DocumentHelper.createElement("string");
elem.addAttribute("name", "bbb");
elem.setText("ppppppp");
// elem.addAttribute("name", "ccc");
elements.add(index,elem);
break;
}
}
OutputFormat format1 = OutputFormat.createPrettyPrint();//缩减型格式
//OutputFormat format = OutputFormat.createCompactFormat();//紧凑型格式
format1.setEncoding("utf-8");//设置编码
// //format.setTrimText(false);//设置text中是否要删除其中多余的空格
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileOutputStream( new File("C:\\Users\\Administrator\\Desktop\\strings.xml")),format1);
// XMLWriter writer = new XMLWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\strings.xml"),format);
xmlWriter.write(document);
xmlWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}