其他分享
首页 > 其他分享> > dom4j——生成xml

dom4j——生成xml

作者:互联网

创建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();
        }
    }

 

标签:xml,String,Service,dom4j,dom,生成,addAttribute,addElement
来源: https://www.cnblogs.com/it-mh/p/11021716.html