dom4 jxml插入
packagecom.huawei.test;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.util.List;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
publicclassInsertElement{
/**
*@paramargs
*@throwsException
*/
publicstaticvoidmain(String[]args)throwsException{
try{
OutputFormatformat=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
SAXReaderreader=newSAXReader();
Documentdocument=reader.read("C:\\Users\\Administrator\\Desktop\\strings.xml");
Elementroot=document.getRootElement();
List<Element>elements=root.elements();
intindex=0;
for(Elementelement:elements){
index++;
if("app_name".equals(element.attributeValue("name"))){
Elementelem=DocumentHelper.createElement("string");
elem.addAttribute("name","bbb");
elem.setText("ppppppp");
//elem.addAttribute("name","ccc");
elements.add(index,elem);
break;
}
}
OutputFormatformat1=OutputFormat.createPrettyPrint();//缩减型格式
//OutputFormatformat=OutputFormat.createCompactFormat();//紧凑型格式
format1.setEncoding("utf-8");//设置编码
////format.setTrimText(false);//设置text中是否要删除其中多余的空格
org.dom4j.io.XMLWriterxmlWriter=neworg.dom4j.io.XMLWriter(
newFileOutputStream(newFile("C:\\Users\\Administrator\\Desktop\\strings.xml")),format1);
//XMLWriterwriter=newXMLWriter(newFileWriter("C:\\Users\\Administrator\\Desktop\\strings.xml"),format);
xmlWriter.write(document);
xmlWriter.close();
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}