1. 程式人生 > 實用技巧 >JAXB XML生成CDATA型別的節點

JAXB XML生成CDATA型別的節點

試了好久才找到一個解決辦法,我是用的JAXB的,如果你們也是用JAXB那麼可以直接借鑑此方法,別的方式你們自行測試吧

第一步:新增一個介面卡類

package com.message.util;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 *AdapterCDATA介面卡
 * @author user
 * @create 2020/7/23
 * @since 1.0.0
 */
public class AdapterCDATA extends XmlAdapter<String, String> {

    @Override
    
public String marshal(String arg0) throws Exception { return "<![CDATA[" + arg0 + "]]>"; } @Override public String unmarshal(String arg0) throws Exception { return arg0; } }

第二步:在Marshaller的物件設定屬性(紅色字型部分)

private void createXML(CEB621Message ceb621Message, String put) {
        File file 
= new File(put); JAXBContext jc = null; try { //根據Person類生成上下文物件 jc = JAXBContext.newInstance(CEB621Message.class); //從上下文中獲取Marshaller物件,用作將bean編組(轉換)為xml Marshaller ma = jc.createMarshaller(); //以下是為生成xml做的一些配置. //設定屬性轉換特殊字串
        ma.setProperty("com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler",
      new CharacterEscapeHandler() {
      public void escape(char[] ch, int start,
int length, boolean isAttVal,Writer writer) throws IOException {
     writer.write(ch, start, length);
    }
    });
           //格式化輸出,即按標籤自動換行,否則就是一行輸出
            ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            //設定編碼(預設編碼就是utf-8)
            ma.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            //是否省略xml頭資訊,預設不省略(false)
            ma.setProperty(Marshaller.JAXB_FRAGMENT, false);
            //生成xml
            ma.marshal(ceb621Message, file);
            System.out.println("生成CEB621Message_" + ceb621Message.getInventory().get(0).getInventoryHead().getCopNo() + ".xml成功");
        } catch (JAXBException e) {
            e.printStackTrace();
            System.out.println("生成CEB621Message_" + ceb621Message.getInventory().get(0).getInventoryHead().getCopNo() + ".xml失敗");
        }
    }

第三步:在需要新增CDATA的JavaBean的屬性上面新增一條註解(紅色部分)

    @XmlJavaTypeAdapter(AdapterCDATA.class)
    @XmlElement(required = true, name = "consigneeAddress")
    protected String consigneeAddress;

然後生成即可,下面是生成的

 <ceb:buyerIdNumber>440105197510183320</ceb:buyerIdNumber>
 <ceb:buyerName>張三</ceb:buyerName>
 <ceb:consigneeAddress><![CDATA[北京市北京市東城區安定門外大街]]></ceb:consigneeAddress>
 <ceb:agentCode>4403468341</ceb:agentCode>

希望幫到有需要的朋友(^_^)