我是靠谱客的博主 阔达云朵,最近开发中收集的这篇文章主要介绍java封装xml_JAVA dom4j 学习三 封装XML,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

packageutils.dom4jutils;importjava.io.FileOutputStream;importjava.util.List;importorg.dom4j.Document;importorg.dom4j.DocumentHelper;importorg.dom4j.Element;importorg.dom4j.io.OutputFormat;importorg.dom4j.io.SAXReader;importorg.dom4j.io.XMLWriter;

public classDom4jUtils {//1:获取document

public staticDocument getDocument(String path){try{//构建解析器

SAXReader saxReader=newSAXReader();//获取document对象

Document document=saxReader.read(path);returndocument;

}catch(Exception e) {

e.printStackTrace();

}return null;

}//2回写xml

public static voidxmlWrites(String path,Document document){try{//获取设置xml格式实例

OutputFormat format=OutputFormat.createPrettyPrint();//读取xml

XMLWriter xmlWriter=new XMLWriter(newFileOutputStream(path),format);//回写到xml文件

xmlWriter.write(document);//关闭文件流

xmlWriter.close();

}catch(Exception e) {

e.printStackTrace();

}

}//3创建元素标签,返回元素对象

public staticElement getElement(String qname,String textString){try{//创建element标签

Element element=DocumentHelper.createElement(qname);//向element标签中加入内容

element.setText(textString);returnelement;

}catch(Exception e) {

e.printStackTrace();

}return null;

}//4增加根节点下的第i个节点增加内容为i的节点

public static void addRootChild(String path,intindex,String qname,String textString){//获取document

Document document=Dom4jUtils.getDocument(path);//获取根节点

Element root=document.getRootElement();//获取root下的所有元素

List list=root.elements();//创建元素标签

Element element=Dom4jUtils.getElement(qname, textString);//把element加入根节点下

list.add(index,element);//回写xml

xmlWrites(path, document);

}//5遍历xml文件之递归

public static voidgetElements(Element element) {

List list=element.elements();//遍历xml

for(int i=0; i

System.out.println(list.get(i));

List l=list.get(i).elements();

System.out.println(l.size());

getElements(list.get(i));

}

}//6遍历xml文件

public static voidgetElements(String path) {//获取document

Document document=Dom4jUtils.getDocument(path);//获取根节点

Element root=document.getRootElement();

getElements(root);

}

}

最后

以上就是阔达云朵为你收集整理的java封装xml_JAVA dom4j 学习三 封装XML的全部内容,希望文章能够帮你解决java封装xml_JAVA dom4j 学习三 封装XML所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部