dom4j——使用dom4j生成xml

使用org.dom4j.Element

创建xml

/**
     * 生成Service.xml文件
     * @param tran  交易对象
     * @param filePath  文件夹路径
     */
    public static void exportServiceXml(List<Transaction> tranList,String filePath){
        String fileurl = filePath + "/Service.xml";
        Document dom = DocumentHelper.createDocument();//添加节点用addElement,添加节点属性用addAttribute,未节点赋值用setText
        Element ServiceTab = dom.addElement("ServiceTab"); //ServiceTab
        Transaction tran = null;
        Iterator<Transaction> it = tranList.iterator();
        while(it.hasNext()){
            tran = it.next();
            String ID = tran.getTransID().substring(2);
            String desc = tran.getTransName();
            
            Element Service = ServiceTab.addElement("Service");//Service
            Service.addAttribute("Name", ID);
            Service.addAttribute("SvcDesc", desc);
            Element NodeClass = Service.addElement("NodeClass"); //NodeClass
            NodeClass.addAttribute("Name", "");
            NodeClass.addAttribute("Desc", "");
            Element ExtCodeExpr = Service.addElement("ExtCodeExpr");
            ExtCodeExpr.setText("<![CDATA[]]>");
            }
        
        ServiceTab.addAttribute("RecNum",String.valueOf(tranList.size()));
        writeXmlFile(dom,fileurl);
    }

生成xml格式

<?xml version="1.0" encoding="UTF-8"?>

<ServiceTab RecNum="1">
  <Service Name="001"
          SvcDesc="测试">
    <NodeClass Name="未分类"
            Desc="未分类"/>
    <ExtCodeExpr><![CDATA[]]></ExtCodeExpr>
  </Service>
</ServiceTab>

 

输出xml文件

/**
Document dom = DocumentHelper.createDocument();//添加节点用addElement,添加节点属性用addAttribute,未节点赋值用setText
*/
public static void writeXmlFile(Document dom,String fileurl){
        //设置生成xml格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码格式
        format.setEncoding("UTF-8");
        File file = new File(fileurl);
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileOutputStream(file),format);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        writer.setEscapeText(false); //关闭字符串中xml特殊字符转义
        try {
            writer.write(dom);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

posted @ 2019-06-14 09:37  !O0O!  阅读(5702)  评论(0编辑  收藏  举报