saxreader读取服务器xml文件,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 listAttr=node.attributes();//当前节点的所有属性的list

for(Attribute attr:listAttr){//遍历当前节点的所有属性

attr.setText("");

}

//递归遍历当前节点所有的子节点

List 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();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值