SAXReader解析xml存到本地文件

public class XmlTest{

public static void main(String[] args) {
XmlTest test=new XmlTest();

Element element;
try {
element=test.testGetRoot("D:\stop.xml");
String x=element.asXML();
String newfileName="D:\stop.xml"+"新.xml";
writeFile(newfileName,formatXml(x,"utf-8",false),"utf-8");

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public Element testGetRoot(String pathName) throws Exception{
SAXReader sax=new SAXReader();//创建一个SAXReader对象
File xmlFile=new File(pathName);//根据指定的路径创建file对象
Document document=sax.read(xmlFile);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
this.getNodes(root);//从根节点开始遍历所有节点
return root;
}

/**
* 递归遍历方法
*
* @param element
*/

public void getNodes(Element node){

//当前节点的名称、文本内容和属性
node.setText("");
List<Attribute> listAttr=node.attributes();//当前节点的所有属性的list
for(Attribute attr:listAttr){//遍历当前节点的所有属性
attr.setText("");
}
//递归遍历当前节点所有的子节点
List<Element> listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
this.getNodes(e);//递归
}
}


public static Document getTempletdoc(String templetName){
SAXReader reader = new SAXReader();
Document templetdoc = null;
try {
templetdoc = reader.read(new File(templetName));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return templetdoc;
}


public static String formatXml(String content, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(charset);
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw, format);
xw.setEscapeText(istrans); //istrans false这样&符号就不会被转义了
try {
xw.write(content);
xw.flush();
xw.close();
} catch (IOException e) {
System.out.println("格式化XML文档发生异常,请检查!");
e.printStackTrace();
}
return sw.toString();
}

public static void writeFile(String filePathAndName, String fileContent,String charsetName) {
try {
File f = new File(filePathAndName);
if (!f.exists()) {
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),charsetName);
BufferedWriter writer=new BufferedWriter(write);
writer.write(fileContent);
writer.close();
} catch (Exception e) {
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}

}

原文地址:https://www.cnblogs.com/wuqiaoqun/p/13091511.html