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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM