您的位置:首页 > 其它

dom4j操作xml的读写操作

2016-02-22 10:19 302 查看
遍历所有节点数据

/**
* <从指定节点开始,递归遍历所有子节点>
* <功能详细描述>
* @param node
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unchecked")
public static void getNodes(Element node){

System.out.println("--------------------");

//当前节点的名称、文本内容和属性
System.out.println("当前节点名称:"+node.getName());//当前节点名称
System.out.println("当前节点的内容:"+node.getTextTrim());//当前节点名称
List<Attribute> listAttr=node.attributes();//当前节点的所有属性的list
for(Attribute attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getValue();//属性的值
System.out.println("属性名称:"+name+"属性值:"+value);
}

//递归遍历当前节点所有的子节点
List<Element> listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
getNodes(e);//递归
}
}


// 保存删除和修改过的数据

/**
* <把改变的domcument对象保存到指定的xml文件中 >
* <功能详细描述>
* @param document
* @param xmlFile
* @throws FileNotFoundException
* @see [类、类#方法、类#成员]
*/
public static void writeDocument(Document document,File xmlFile) throws FileNotFoundException
{
//创建输出流
Writer writer = new OutputStreamWriter(new FileOutputStream(xmlFile));
//获取输出的指定格式
OutputFormat format = OutputFormat.createPrettyPrint();
//设置编码 ,确保解析的xml为UTF-8格式
format.setEncoding("UTF-8");
//XMLWriter 指定输出文件以及格式
XMLWriter xmlWriter = new XMLWriter(writer, format);

try
{
//把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)
xmlWriter.write(document);
xmlWriter.flush();
xmlWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}

调用和执行遍历方法和保存方法

public static void main(String[] args) throws DocumentException
    {
        SAXReader sax = new SAXReader();
        
        File xmlFile = new File("e:\\datasource.xml");
        //获取文档对象信息
        Document document = sax.read(xmlFile);
        //获取根节点信息
        Element root = document.getRootElement();
        //遍历xml文件信息
        getNodes(root);
        //获取指定的节点数据对象
        Element beanElement = root.element("bean");
        //获取bean节点的id属性对象
        Attribute att = beanElement.attribute("id");
        //移除id属性的对象
        beanElement.remove(att);
        //增加bean节点 新的属性
        beanElement.addAttribute("name", "新的属性");
        
        try
        {
            //将删除的节点属性、新增的节点属性 写入xmlFile文件中
            writeDocument(document, xmlFile);
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dom4j 遍历 dom xml