JAVA使用Dom4j实现字符串和xml文件相互转换

在文章《JAVA 使用Dom4j 解析XML》中,介绍了使用Dom44j解析XML,比如节点的解析遍历、节点的增加、删除、写入文件等操作,本文我们继续使用dom4j实现xml字符串与xml文件之间的转换。

1.xml文档或节点转换为字符串

public void test5()throws Exception{  
        //创建SAXReader对象  
        SAXReader reader = new SAXReader();  
        //读取文件 转换成Document  
        Document document = reader.read(new File("C:/s.xml"));  
        //document转换为String字符串  
        String documentStr = document.asXML();  
        System.out.println("document 字符串:" + documentStr);  
        //获取根节点  
        Element root = document.getRootElement();  
        //根节点转换为String字符串  
        String rootStr = root.asXML();  
        System.out.println("root 字符串:" + rootStr);  
        //获取其中student1节点  
        Element student1Node = root.element("student1");  
        //student1节点转换为String字符串  
        String student1Str = student1Node.asXML();  
        System.out.println("student1 字符串:" + student1Str);  
    }

XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>  
<students>  
    <student1 id="001">  
        <微信公众号>@残缺的孤独</微信公众号>  
        <学号>20140101</学号>  
        <地址>北京海淀区</地址>  
        <座右铭>要么强大,要么听话</座右铭>  
    </student1>  
    <student2 id="002">  
        <新浪微博>@残缺的孤独</新浪微博>  
        <学号>20140102</学号>  
        <地址>北京朝阳区</地址>  
        <座右铭>在哭泣中学会坚强</座右铭>  
    </student2>  
</students>

2.xml字符串转换为Document对象

public void test6()throws Exception{  
        String xmlStr = "<employee><empname>@残缺的孤独</empname><age>25</age><title>软件开发工程师</title></employee>";  
        Document document = DocumentHelper.parseText(xmlStr);  
        //写入emp1.xml文件  
        writerDocumentToNewFile(document);  
    }
3.使用dom4j新建document对象,并写入文件中

public void test7()throws Exception{  
        Document document = DocumentHelper.createDocument();  
        Element rootElement = document.addElement("employee");  
        Element empName = rootElement.addElement("empname");  
        empName.setText("@残缺的孤独");  
        Element empAge = rootElement.addElement("age");  
        empAge.setText("25");  
        Element empTitle = rootElement.addElement("title");  
        empTitle.setText("软件开发工程师");  
        //写入文档emp.xml  
        writerDocumentToNewFile(document);  
    }







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值